using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Security.Principal;

namespace MemGuardian
{
    /// <summary>
    /// MemGuardian设置窗体类
    /// 提供程序的所有配置选项，包括启动设置、内存清理配置、UI选项等
    /// 采用分页式布局，将设置分为多个类别便于用户管理
    /// </summary>
    public partial class SettingsForm : Form
    {
        #region UI控件字段
        /// <summary>
        /// 左侧面板，包含设置分类列表
        /// </summary>
        private Panel leftPanel = null!;
        
        /// <summary>
        /// 右侧面板，显示当前选中分类的具体设置选项
        /// </summary>
        private Panel rightPanel = null!;
        
        /// <summary>
        /// 设置分类列表框，用于切换不同的设置页面
        /// </summary>
        private ListBox categoryListBox = null!;
        
        /// <summary>
        /// 是否允许ListBox选择改变，用于防止空白区域点击导致的闪烁
        /// </summary>
        private bool allowSelectionChange = true;
        
         /// <summary>
         /// 保存按钮，应用所有设置更改
         /// </summary>
         private Button saveButton = null!;
         
         /// <summary>
         /// 取消按钮，放弃所有设置更改并关闭窗体
         /// </summary>
         private Button cancelButton = null!;
        #endregion

        #region 常规设置字段
        /// <summary>
        /// 自动启动复选框，控制程序是否随系统启动
        /// </summary>
        private CheckBox autoStartCheckBox = null!;
        
        /// <summary>
        /// 窗口置顶复选框，控制主窗体是否始终保持在最前面
        /// </summary>
        private CheckBox alwaysOnTopCheckBox = null!;
        
        /// <summary>
        /// 启动时最小化复选框，控制程序启动时是否最小化到托盘
        /// </summary>
        private CheckBox minimizeStartupCheckBox = null!;
        
        /// <summary>
        /// 关闭到托盘复选框，控制点击关闭按钮时是否最小化到托盘而不是退出程序
        /// </summary>
        private CheckBox closeToTrayCheckBox = null!;
        
        /// <summary>
        /// 手动确认复选框，控制执行内存清理前是否显示确认对话框
        /// </summary>
        private CheckBox manualConfirmCheckBox = null!;
        
        /// <summary>
        /// 跳过UAC提示复选框，控制是否跳过用户账户控制提示
        /// </summary>
        private CheckBox skipUacPromptCheckBox = null!;
        
        /// <summary>
        /// 标志，用于区分是用户操作还是程序加载状态，避免在加载时显示安全警告
        /// </summary>
        private bool isLoadingSettings = false;
        
        /// <summary>
        /// 程序启动时的UAC跳过状态
        /// 用于区分运行时取消UAC和重新启动后UAC被取消的情况
        /// </summary>
        private bool skipUacPromptAtStartup = false;
        
        /// <summary>
        /// 显示内存清理气泡复选框，控制是否在内存清理完成后显示气泡提示
        /// </summary>
        private CheckBox showMemoryCleanupBubbleCheckBox = null!;
        
        /// <summary>
        /// 启用内存清理声音复选框，控制是否在内存清理完成后播放提示音
        /// </summary>
        private CheckBox enableMemoryCleanupSoundCheckBox = null!;
        
        /// <summary>
        /// 左键动作下拉框，设置托盘图标左键点击时的行为
        /// </summary>
        private ComboBox leftClickActionComboBox = null!;
        
         /// <summary>
         /// 中键动作下拉框，设置托盘图标中键点击时的行为
         /// </summary>
         private ComboBox middleClickActionComboBox = null!;
         
         /// <summary>
         /// 主题下拉框，设置应用程序主题（浅色主题、深色主题、自动跟随系统）
         /// </summary>
         private ComboBox themeComboBox = null!;
         
         /// <summary>
         /// 托盘图标文本颜色按钮，用于选择文本颜色
         /// </summary>
         private Button trayTextColorButton = null!;
         
         /// <summary>
         /// 托盘图标正常背景颜色按钮，用于选择正常状态背景颜色
         /// </summary>
         private Button trayNormalBackgroundColorButton = null!;
         
         /// <summary>
         /// 托盘图标警告级别背景颜色按钮，用于选择警告状态背景颜色
         /// </summary>
         private Button trayWarningBackgroundColorButton = null!;
         
         /// <summary>
         /// 托盘图标危险级别背景颜色按钮，用于选择危险状态背景颜色
         /// </summary>
         private Button trayDangerBackgroundColorButton = null!;
         #endregion

        #region 内存清理设置字段
        /// <summary>
        /// 自动内存清理复选框，控制是否启用自动内存清理功能
        /// </summary>
        private CheckBox autoMemoryCleanupCheckBox = null!;
        
        /// <summary>
        /// 启用清理间隔复选框，控制是否启用定时自动清理
        /// </summary>
        private CheckBox enableCleanupIntervalCheckBox = null!;
        
        /// <summary>
        /// 内存清理阈值数值框，设置触发自动清理的内存使用率阈值（百分比）
        /// </summary>
        private NumericUpDown memoryCleanupThresholdNumericUpDown = null!;
        
        /// <summary>
        /// 启用内存阈值复选框，控制是否启用基于内存使用率的自动清理
        /// </summary>
        private CheckBox enableMemoryThresholdCheckBox = null!;
        
        /// <summary>
        /// 深度内存清理复选框，控制是否启用深度内存清理模式
        /// </summary>
        private CheckBox deepMemoryCleanupCheckBox = null!;
        
        /// <summary>
        /// 系统缓存清理复选框，控制是否清理系统文件缓存
        /// </summary>
        private CheckBox systemCacheCleanupCheckBox = null!;
        
        /// <summary>
        /// 进程内存清理复选框，控制是否清理进程工作集
        /// </summary>
        private CheckBox processMemoryCleanupCheckBox = null!;
        
        /// <summary>
        /// 清理间隔数值框，设置自动清理的时间间隔（分钟）
        /// </summary>
        private NumericUpDown cleanupIntervalNumericUpDown = null!;
        
        /// <summary>
        /// 显示清理进度复选框，控制是否显示内存清理进度提示
        /// </summary>
        private CheckBox showCleanupProgressCheckBox = null!;
        
        /// <summary>
        /// 自动清理冷却时间数值框，设置连续自动清理之间的最小间隔（分钟）
        /// </summary>
        private NumericUpDown autoCleanupCooldownNumericUpDown = null!;
        
        /// <summary>
        /// 启用自动清理冷却复选框，控制是否启用自动清理冷却时间限制
        /// </summary>
        private CheckBox enableAutoCleanupCooldownCheckBox = null!;
        #endregion

        #region 内存清理区域设置字段
        /// <summary>
        /// 工作集清理复选框，控制是否清理进程工作集内存
        /// </summary>
        private CheckBox workingSetCleanupCheckBox = null!;
        
        /// <summary>
        /// 系统文件缓存清理复选框，控制是否清理系统文件缓存
        /// </summary>
        private CheckBox systemFileCacheCleanupCheckBox = null!;
        
        /// <summary>
        /// 已修改页列表清理复选框，控制是否清理已修改的页面列表
        /// </summary>
        private CheckBox modifiedPageListCleanupCheckBox = null!;
        
        /// <summary>
        /// 待机列表清理复选框，控制是否清理待机内存列表
        /// </summary>
        private CheckBox standbyListCleanupCheckBox = null!;
        
        /// <summary>
        /// 无优先级待机列表清理复选框，控制是否清理无优先级的待机内存
        /// </summary>
        private CheckBox standbyListNoPriorityCleanupCheckBox = null!;
        
        /// <summary>
        /// 已修改文件缓存清理复选框，控制是否清理已修改的文件缓存
        /// </summary>
        private CheckBox modifiedFileCacheCleanupCheckBox = null!;
        
        /// <summary>
        /// 注册表缓存清理复选框，控制是否清理注册表缓存
        /// </summary>
        private CheckBox registryCacheCleanupCheckBox = null!;
        
        /// <summary>
        /// 合并内存列表清理复选框，控制是否清理合并的内存列表
        /// </summary>
        private CheckBox mergedMemoryListCleanupCheckBox = null!;
        #endregion

        /// <summary>
        /// 主窗体引用，用于与主程序进行交互
        /// </summary>
        private Form1? mainForm;

        /// <summary>
        /// 当前是否为夜间模式
        /// </summary>
        private bool isDarkMode = false;

        /// <summary>
        /// 默认构造函数
        /// 初始化设置窗体并加载当前设置
        /// </summary>
        public SettingsForm()
        {
            InitializeComponent();
            LoadSettings();
            InitializeDarkMode();
        }

        /// <summary>
        /// 带主窗体引用的构造函数
        /// 用于从主窗体打开设置窗体，建立窗体间的关联关系
        /// </summary>
        /// <param name="owner">主窗体实例，用于窗体间的交互</param>
        public SettingsForm(Form1 owner) : this()
        {
            this.mainForm = owner;
            this.Owner = owner;
            // 从主窗体同步夜间模式状态
            SyncDarkModeFromMainForm();
            // 初始化UAC状态
            InitializeSkipUacPromptStatus();
        }

        /// <summary>
        /// 初始化设置窗体组件
        /// 创建左右分栏布局的设置界面，包括分类列表和设置内容区域
        /// </summary>
        /// <remarks>
        /// 窗体布局设计：
        /// - 左侧：分类列表（常规设置、显示设置、内存管理、通知反馈）
        /// - 右侧：对应分类的具体设置选项
        /// - 底部：操作按钮（关闭、重置）
        /// 
        /// 该方法是Windows Forms设计器自动生成的，包含所有控件的初始化代码
        /// </remarks>
        private void InitializeComponent()
        {
             // 创建主要容器控件
             leftPanel = new Panel();           // 左侧分类面板
             categoryListBox = new ListBox();   // 分类列表控件
             rightPanel = new Panel();          // 右侧设置面板
             cancelButton = new Button();       // 关闭按钮
             saveButton = new Button();         // 重置按钮
            
            // 暂停布局更新，提高初始化性能
            leftPanel.SuspendLayout();
            rightPanel.SuspendLayout();
            SuspendLayout();
            // 
            // leftPanel
            // 
            leftPanel.BackColor = Color.FromArgb(255, 255, 255);
            leftPanel.Controls.Add(categoryListBox);
            leftPanel.Dock = DockStyle.Left;
            leftPanel.Location = new Point(0, 0);
            leftPanel.Margin = new Padding(4);
            leftPanel.Name = "leftPanel";
            leftPanel.Size = new Size(129, 469);
            leftPanel.TabIndex = 0;
            // 
            // categoryListBox
            // 
            categoryListBox.BackColor = Color.FromArgb(255, 255, 255);
            categoryListBox.BorderStyle = BorderStyle.FixedSingle;
            categoryListBox.Dock = DockStyle.Fill;
            categoryListBox.DrawMode = DrawMode.OwnerDrawFixed;
            categoryListBox.Font = new Font("微软雅黑", 11F);
            categoryListBox.ItemHeight = 32;
            categoryListBox.Items.AddRange(new object[] { "常规设置", "显示设置", "内存管理", "通知反馈" });
            categoryListBox.Location = new Point(0, 0);
            categoryListBox.Margin = new Padding(10, 9, 10, 9);
            categoryListBox.Name = "categoryListBox";
            categoryListBox.Size = new Size(129, 469);
            categoryListBox.TabIndex = 0;
            categoryListBox.DrawItem += CategoryListBox_DrawItem;
            categoryListBox.SelectedIndexChanged += CategoryListBox_SelectedIndexChanged;
            categoryListBox.MouseClick += CategoryListBox_MouseClick;
            // 
            // rightPanel
            // 
            rightPanel.BackColor = Color.FromArgb(240, 240, 240);
            rightPanel.Controls.Add(cancelButton);
            rightPanel.Controls.Add(saveButton);
            rightPanel.Dock = DockStyle.Fill;
            rightPanel.Location = new Point(129, 0);
            rightPanel.Margin = new Padding(4);
            rightPanel.Name = "rightPanel";
            rightPanel.Padding = new Padding(15, 14, 15, 14);
            rightPanel.Size = new Size(420, 469);
            rightPanel.TabIndex = 1;
             // 
             // cancelButton
             // 
             cancelButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
             cancelButton.BackColor = Color.Transparent;
             cancelButton.FlatAppearance.BorderSize = 1;
             cancelButton.FlatAppearance.BorderColor = Color.FromArgb(200, 200, 200);
             cancelButton.FlatAppearance.MouseOverBackColor = Color.FromArgb(230, 244, 255);
             cancelButton.FlatStyle = FlatStyle.Flat;
             cancelButton.Font = new Font("微软雅黑", 10F);
             cancelButton.ForeColor = Color.Black;
             cancelButton.Location = new Point(24, 426);
             cancelButton.Margin = new Padding(4);
             cancelButton.Name = "cancelButton";
             cancelButton.Size = new Size(74, 30);
             cancelButton.TabIndex = 2;
             cancelButton.Text = "关闭";
             cancelButton.UseVisualStyleBackColor = false;
             cancelButton.Click += CloseButton_Click;
             // 
             // saveButton
             // 
             saveButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
             saveButton.BackColor = Color.Transparent;
             saveButton.FlatAppearance.BorderSize = 1;
             saveButton.FlatAppearance.BorderColor = Color.FromArgb(200, 200, 200);
             saveButton.FlatAppearance.MouseOverBackColor = Color.FromArgb(230, 244, 255);
             saveButton.FlatStyle = FlatStyle.Flat;
             saveButton.Font = new Font("微软雅黑", 10F);
             saveButton.ForeColor = Color.Black;
             saveButton.Location = new Point(326, 428);
             saveButton.Margin = new Padding(4);
             saveButton.Name = "saveButton";
             saveButton.Size = new Size(74, 30);
             saveButton.TabIndex = 1;
             saveButton.Text = "重置";
             saveButton.UseVisualStyleBackColor = false;
             saveButton.Click += ResetButton_Click;
            // 
            // SettingsForm
            // 
            AutoScaleDimensions = new SizeF(9F, 20F);
            AutoScaleMode = AutoScaleMode.Font;
            BackColor = Color.FromArgb(248, 249, 250);
            // 设置最小尺寸，确保在不同分辨率下都能正常显示
            MinimumSize = new Size(600, 500);
            ClientSize = new Size(600, 500);
            Controls.Add(rightPanel);
            Controls.Add(leftPanel);
            FormBorderStyle = FormBorderStyle.Sizable;
            Margin = new Padding(4);
            MaximizeBox = false;
            MinimizeBox = false;
            Name = "SettingsForm";
            ShowInTaskbar = false;
            StartPosition = FormStartPosition.CenterParent;
            Text = "Mem Guardian - 系统设置";
            // 添加窗体大小调整事件
            Resize += SettingsForm_Resize;
            leftPanel.ResumeLayout(false);
            rightPanel.ResumeLayout(false);
            ResumeLayout(false);
        }

        // InitializeSettingsControls方法已删除，因为大部分控件字段已被删除

        // SetupControlsProperties方法已删除，因为大部分控件已被删除

        // 所有Setup方法已删除，因为对应的控件字段已被删除

        /// <summary>
        /// 分类列表选择改变事件处理
        /// 当用户点击左侧分类列表中的不同分类时，动态切换右侧显示对应的设置内容
        /// </summary>
        /// <param name="sender">事件发送者（分类列表控件）</param>
        /// <param name="e">事件参数</param>
        /// <remarks>
        /// 该方法实现了动态内容切换功能：
        /// 1. 清除右侧面板的所有控件（保留底部按钮）
        /// 2. 根据选中的分类名称，调用对应的设置显示方法
        /// 3. 支持4个主要分类：常规设置、显示设置、内存管理、通知反馈
        /// 4. 每个分类都有独立的设置界面和功能
        /// </remarks>
        private void CategoryListBox_MouseClick(object? sender, MouseEventArgs e)
        {
            try
            {
                // 获取点击位置对应的项目索引
                int clickedIndex = categoryListBox.IndexFromPoint(e.Location);
                
                // 如果点击在空白区域（索引为-1），阻止选择改变
                if (clickedIndex == -1)
                {
                    allowSelectionChange = false;
                    // 如果当前没有选中项，默认选中第一项
                    if (categoryListBox.SelectedIndex == -1 && categoryListBox.Items.Count > 0)
                    {
                        allowSelectionChange = true;
                        categoryListBox.SelectedIndex = 0;
                    }
                    return;
                }
                
                // 如果点击在有效项目上，允许选择改变
                allowSelectionChange = true;
                categoryListBox.SelectedIndex = clickedIndex;
            }
            catch
            {
                // 静默处理点击事件异常
                allowSelectionChange = true;
            }
        }

        private void CategoryListBox_SelectedIndexChanged(object? sender, EventArgs e)
        {
            // 如果不允许选择改变，直接返回，防止闪烁
            if (!allowSelectionChange)
            {
                return;
            }

            // 如果选中索引无效（-1），恢复之前的选择，防止闪烁
            if (categoryListBox.SelectedIndex == -1)
            {
                // 如果当前没有有效选择，默认选择第一项
                if (categoryListBox.Items.Count > 0)
                {
                    categoryListBox.SelectedIndex = 0;
                }
                return;
            }

            // 清除当前设置面板的所有控件，准备显示新的设置内容
            rightPanel.Controls.Clear();
            // 重新添加底部操作按钮（关闭、重置）
            rightPanel.Controls.Add(cancelButton);
            rightPanel.Controls.Add(saveButton);

            // 根据选中的分类显示相应的设置内容
            if (categoryListBox.SelectedIndex >= 0)
            {
                // 获取选中的分类名称
                string selectedCategory = categoryListBox.Items[categoryListBox.SelectedIndex].ToString() ?? "";

                // 根据分类名称调用对应的设置显示方法
                switch (selectedCategory)
                {
                    case "常规设置":
                        ShowProgramBehaviorSettings();        // 显示常规设置（启动选项、基本行为等）
                        break;
                    case "显示设置":
                        ShowInteractionControlSettings();        // 显示显示设置（鼠标操作、主题等）
                        break;
                    case "内存管理":
                        ShowMemoryManagementSettings();  // 显示内存管理设置（自动清理、清理区域等）
                        break;
                    case "通知反馈":
                        ShowNotificationFeedbackSettings();   // 显示通知反馈设置（气泡、声音等）
                        break;
                }
            }
        }

        private void ShowProgramBehaviorSettings()
        {
            // 初始化控件
            InitializeGeneralSettingsControls();

            // 创建标题
            var titleLabel = CreateCategoryLabel("常规设置", new Point(20, 10));
            rightPanel.Controls.Add(titleLabel);

            // 创建设置项
            int yPosition = 30;

            // 开机自启
            var autoStartPanel = CreateSettingItemPanel("开机自启", autoStartCheckBox, yPosition);
            rightPanel.Controls.Add(autoStartPanel);
            yPosition += 16 + 16; // 面板高度 + 间距

            // 最小化启动
            var minimizeStartupPanel = CreateSettingItemPanel("最小化启动（不显示窗口）", minimizeStartupCheckBox, yPosition);
            rightPanel.Controls.Add(minimizeStartupPanel);
            yPosition += 16 + 16; // 面板高度 + 间距

            // 关闭最小化到托盘
            var closeToTrayPanel = CreateSettingItemPanel("关闭最小化到托盘", closeToTrayCheckBox, yPosition);
            rightPanel.Controls.Add(closeToTrayPanel);
            yPosition += 16 + 16; // 面板高度 + 间距

            // 窗口始终置顶
            var alwaysOnTopPanel = CreateSettingItemPanel("窗口始终置顶", alwaysOnTopCheckBox, yPosition);
            rightPanel.Controls.Add(alwaysOnTopPanel);
            yPosition += 16 + 16; // 面板高度 + 间距

            // 跳过UAC提示
            var skipUacPromptPanel = CreateSettingItemPanel("跳过\"用户账户控制（UAC）\"提示", skipUacPromptCheckBox, yPosition);
            rightPanel.Controls.Add(skipUacPromptPanel);
            yPosition += 16 + 16; // 面板高度 + 间距

            // 手动确认
            var manualConfirmPanel = CreateSettingItemPanel("在内存清理前手动确认", manualConfirmCheckBox, yPosition);
            rightPanel.Controls.Add(manualConfirmPanel);

            // 加载当前设置
            LoadGeneralSettings();
        }

         private void ShowInteractionControlSettings()
         {
             // 初始化控件
             InitializeGeneralSettingsControls();
             
             // 创建标题
             var titleLabel = CreateCategoryLabel("外观设置", new Point(20, 10));
             rightPanel.Controls.Add(titleLabel);
             
             // 创建设置项
             int yPosition = 30;
             
             // 主题设置
             var themePanel = CreateComboBoxSettingPanel("主题", themeComboBox, yPosition);
             rightPanel.Controls.Add(themePanel);
             yPosition += 40 + 16; // 面板高度 + 间距
             
             // 鼠标控制标题
             var mouseControlTitleLabel = CreateCategoryLabel("鼠标控制", new Point(20, yPosition));
             rightPanel.Controls.Add(mouseControlTitleLabel);
             yPosition += 30;

             // 左键单击设置
             var leftClickPanel = CreateComboBoxSettingPanel("左键单击", leftClickActionComboBox, yPosition);
             rightPanel.Controls.Add(leftClickPanel);
             yPosition += 48;

             // 中间单击设置
             var middleClickPanel = CreateComboBoxSettingPanel("中间单击", middleClickActionComboBox, yPosition);
             rightPanel.Controls.Add(middleClickPanel);
             yPosition += 48 + 16; // 面板高度 + 间距
             
             // 个性化标题
             var personalizationTitleLabel = CreateCategoryLabel("个性化", new Point(20, yPosition));
             rightPanel.Controls.Add(personalizationTitleLabel);
             yPosition += 30;
             
             // 托盘图标文本颜色
             var trayTextColorPanel = CreateColorSettingPanel("托盘文本颜色", trayTextColorButton, yPosition);
             rightPanel.Controls.Add(trayTextColorPanel);
             yPosition += 40;
             
             // 托盘图标正常背景颜色
             var trayNormalBackgroundColorPanel = CreateColorSettingPanel("托盘正常背景颜色", trayNormalBackgroundColorButton, yPosition);
             rightPanel.Controls.Add(trayNormalBackgroundColorPanel);
             yPosition += 40;
             
             // 托盘图标警告级别背景颜色
             var trayWarningBackgroundColorPanel = CreateColorSettingPanel("托盘警告级别背景颜色", trayWarningBackgroundColorButton, yPosition);
             rightPanel.Controls.Add(trayWarningBackgroundColorPanel);
             yPosition += 40;
             
             // 托盘图标危险级别背景颜色
             var trayDangerBackgroundColorPanel = CreateColorSettingPanel("托盘危险级别背景颜色", trayDangerBackgroundColorButton, yPosition);
             rightPanel.Controls.Add(trayDangerBackgroundColorPanel);
             
             // 加载当前设置
             LoadDisplaySettings();
         }

        private void ShowMemoryManagementSettings()
        {
            // 初始化控件
            InitializeMemoryCleanupControls();

            // 创建标题
            var titleLabel = CreateCategoryLabel("内存管理设置", new Point(20, 10));
            rightPanel.Controls.Add(titleLabel);

            // 加载当前设置
            LoadMemoryCleanupSettings();

            // 创建设置项
            int yPosition = 30;

            // 启用清理间隔（复选框 + 数值输入框在同一行）
            var enableCleanupIntervalPanel = CreateSettingItemPanel("自动清理间隔 (分钟)", enableCleanupIntervalCheckBox, cleanupIntervalNumericUpDown, yPosition);
            rightPanel.Controls.Add(enableCleanupIntervalPanel);
            yPosition += 40;

            // 启用内存阈值（复选框 + 数值输入框在同一行）
            var enableMemoryThresholdPanel = CreateSettingItemPanel("内存使用率超过时自动清理 (%)", enableMemoryThresholdCheckBox, memoryCleanupThresholdNumericUpDown, yPosition);
            rightPanel.Controls.Add(enableMemoryThresholdPanel);
            yPosition += 40;

            // 自动清理冷却时间（复选框 + 数值输入框在同一行）
            var enableAutoCleanupCooldownPanel = CreateSettingItemPanel("自动清理冷却时间 (秒)", enableAutoCleanupCooldownCheckBox, autoCleanupCooldownNumericUpDown, yPosition);
            rightPanel.Controls.Add(enableAutoCleanupCooldownPanel);
            yPosition += 56;

            // 要清理的内存区域标题
            var memoryRegionTitleLabel = CreateCategoryLabel("要清理的内存区域", new Point(20, yPosition));
            rightPanel.Controls.Add(memoryRegionTitleLabel);
            yPosition += 26;

            // 工作集
            var workingSetPanel = CreateSettingItemPanel("工作集", workingSetCleanupCheckBox, yPosition);
            rightPanel.Controls.Add(workingSetPanel);
            yPosition += 16 + 8;

            // 系统文件缓存
            var systemFileCachePanel = CreateSettingItemPanel("系统文件缓存", systemFileCacheCleanupCheckBox, yPosition);
            rightPanel.Controls.Add(systemFileCachePanel);
            yPosition += 16 + 8;

            // 已修改页列表*
            var modifiedPageListPanel = CreateSettingItemPanel("已修改页列表*", modifiedPageListCleanupCheckBox, yPosition);
            rightPanel.Controls.Add(modifiedPageListPanel);
            yPosition += 16 + 8;

            // 待机列表*
            var standbyListPanel = CreateSettingItemPanel("待机列表*", standbyListCleanupCheckBox, yPosition);
            rightPanel.Controls.Add(standbyListPanel);
            yPosition += 16 + 8;

            // 待机列表（无优先级）
            var standbyListNoPriorityPanel = CreateSettingItemPanel("待机列表（无优先级）", standbyListNoPriorityCleanupCheckBox, yPosition);
            rightPanel.Controls.Add(standbyListNoPriorityPanel);
            yPosition += 16 + 8;

            // 已修改文件缓存
            var modifiedFileCachePanel = CreateSettingItemPanel("已修改文件缓存", modifiedFileCacheCleanupCheckBox, yPosition);
            rightPanel.Controls.Add(modifiedFileCachePanel);
            yPosition += 16 + 8;

            // 注册表缓存（Windows 8.1 及以上）
            var registryCachePanel = CreateSettingItemPanel("注册表缓存（Windows 8.1 及以上）", registryCacheCleanupCheckBox, yPosition);
            rightPanel.Controls.Add(registryCachePanel);
            yPosition += 16 + 8;

            // 合并内存列表（Windows 10 及以上）
            var mergedMemoryListPanel = CreateSettingItemPanel("合并内存列表（Windows 10 及以上）", mergedMemoryListCleanupCheckBox, yPosition);
            rightPanel.Controls.Add(mergedMemoryListPanel);
        }

        private void ShowNotificationFeedbackSettings()
        {
            // 初始化控件
            InitializeGeneralSettingsControls();
            
            // 创建标题
            var titleLabel = CreateCategoryLabel("通知反馈设置", new Point(20, 10));
            rightPanel.Controls.Add(titleLabel);

            // 创建设置项
            int yPosition = 30;

            // 显示内存清理结果气泡
            var showMemoryCleanupBubblePanel = CreateSettingItemPanel("显示内存清理结果气泡", showMemoryCleanupBubbleCheckBox, yPosition);
            rightPanel.Controls.Add(showMemoryCleanupBubblePanel);
            yPosition += 16 + 16; // 面板高度 + 间距

            // 开启内存清理声音通知
            var enableMemoryCleanupSoundPanel = CreateSettingItemPanel("开启内存清理声音通知", enableMemoryCleanupSoundCheckBox, yPosition);
            rightPanel.Controls.Add(enableMemoryCleanupSoundPanel);
            yPosition += 16 + 16; // 面板高度 + 间距

            // 加载当前设置
            LoadGeneralSettings();
        }

        private void InitializeGeneralSettingsControls()
        {
            // 初始化复选框控件
            alwaysOnTopCheckBox = new CheckBox();
            autoStartCheckBox = new CheckBox();
            minimizeStartupCheckBox = new CheckBox();
            closeToTrayCheckBox = new CheckBox();
            manualConfirmCheckBox = new CheckBox();
            skipUacPromptCheckBox = new CheckBox();
            showMemoryCleanupBubbleCheckBox = new CheckBox();
            enableMemoryCleanupSoundCheckBox = new CheckBox();

             // 初始化鼠标控制控件
             leftClickActionComboBox = new ComboBox();
             middleClickActionComboBox = new ComboBox();
             
             // 初始化主题控件
             themeComboBox = new ComboBox();
             
             // 初始化颜色选择按钮
             trayTextColorButton = new Button();
             trayNormalBackgroundColorButton = new Button();
             trayWarningBackgroundColorButton = new Button();
             trayDangerBackgroundColorButton = new Button();
 
             // 设置控件属性
             SetupGeneralCheckBoxProperties();
        }

        private void InitializeMemoryCleanupControls()
        {
            // 初始化内存清理控件
            autoMemoryCleanupCheckBox = new CheckBox();
            enableCleanupIntervalCheckBox = new CheckBox();
            memoryCleanupThresholdNumericUpDown = new NumericUpDown();
            enableMemoryThresholdCheckBox = new CheckBox();
            deepMemoryCleanupCheckBox = new CheckBox();
            systemCacheCleanupCheckBox = new CheckBox();
            processMemoryCleanupCheckBox = new CheckBox();
            cleanupIntervalNumericUpDown = new NumericUpDown();
            showCleanupProgressCheckBox = new CheckBox();
            autoCleanupCooldownNumericUpDown = new NumericUpDown();
            enableAutoCleanupCooldownCheckBox = new CheckBox();

            // 初始化要清理的内存区域控件
            workingSetCleanupCheckBox = new CheckBox();
            systemFileCacheCleanupCheckBox = new CheckBox();
            modifiedPageListCleanupCheckBox = new CheckBox();
            standbyListCleanupCheckBox = new CheckBox();
            standbyListNoPriorityCleanupCheckBox = new CheckBox();
            modifiedFileCacheCleanupCheckBox = new CheckBox();
            registryCacheCleanupCheckBox = new CheckBox();
            mergedMemoryListCleanupCheckBox = new CheckBox();

            // 设置控件属性
            SetupMemoryCleanupControlProperties();
        }

        private void SetupGeneralCheckBoxProperties()
        {
            // 窗口始终置顶
            alwaysOnTopCheckBox.Font = new Font("微软雅黑", 12F);
            alwaysOnTopCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            alwaysOnTopCheckBox.AutoSize = true;
            alwaysOnTopCheckBox.CheckedChanged += AlwaysOnTopCheckBox_CheckedChanged;

            // 开机自启
            autoStartCheckBox.Font = new Font("微软雅黑", 12F);
            autoStartCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            autoStartCheckBox.AutoSize = true;
            autoStartCheckBox.CheckedChanged += AutoStartCheckBox_CheckedChanged;

            // 最小化启动
            minimizeStartupCheckBox.Font = new Font("微软雅黑", 12F);
            minimizeStartupCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            minimizeStartupCheckBox.AutoSize = true;
            minimizeStartupCheckBox.CheckedChanged += MinimizeStartupCheckBox_CheckedChanged;

            // 关闭最小化到托盘
            closeToTrayCheckBox.Font = new Font("微软雅黑", 12F);
            closeToTrayCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            closeToTrayCheckBox.AutoSize = true;
            closeToTrayCheckBox.CheckedChanged += CloseToTrayCheckBox_CheckedChanged;

            // 手动确认
            manualConfirmCheckBox.Font = new Font("微软雅黑", 12F);
            manualConfirmCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            manualConfirmCheckBox.AutoSize = true;
            manualConfirmCheckBox.CheckedChanged += ManualConfirmCheckBox_CheckedChanged;

            // 跳过UAC提示
            skipUacPromptCheckBox.Font = new Font("微软雅黑", 12F);
            skipUacPromptCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            skipUacPromptCheckBox.AutoSize = true;
            skipUacPromptCheckBox.UseVisualStyleBackColor = false; // 禁用系统默认样式，确保自定义颜色生效
            skipUacPromptCheckBox.CheckedChanged += SkipUacPromptCheckBox_CheckedChanged;

            // 显示内存清理结果气泡
            showMemoryCleanupBubbleCheckBox.Font = new Font("微软雅黑", 12F);
            showMemoryCleanupBubbleCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            showMemoryCleanupBubbleCheckBox.AutoSize = true;
            showMemoryCleanupBubbleCheckBox.CheckedChanged += ShowMemoryCleanupBubbleCheckBox_CheckedChanged;

            // 开启内存清理声音通知
            enableMemoryCleanupSoundCheckBox.Font = new Font("微软雅黑", 12F);
            enableMemoryCleanupSoundCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            enableMemoryCleanupSoundCheckBox.AutoSize = true;
            enableMemoryCleanupSoundCheckBox.CheckedChanged += EnableMemoryCleanupSoundCheckBox_CheckedChanged;

             // 重新检查当前主题状态，确保颜色正确
             bool currentDarkMode = isDarkMode;
             if (mainForm != null)
             {
                 currentDarkMode = mainForm.IsDarkModeEnabled();
             }

             // 鼠标控制 - 左键单击
             leftClickActionComboBox.Font = new Font("微软雅黑", 12F);
             leftClickActionComboBox.ForeColor = currentDarkMode ? Color.White : Color.FromArgb(51, 51, 51);
             leftClickActionComboBox.BackColor = currentDarkMode ? Color.Black : Color.White;
             leftClickActionComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
             leftClickActionComboBox.DrawMode = DrawMode.OwnerDrawFixed;
             leftClickActionComboBox.Items.AddRange(new object[] { "显示\\隐藏", "内存清理", "打开任务管理器" });
             leftClickActionComboBox.SelectedIndex = 0; // 默认：显示\隐藏
             leftClickActionComboBox.DrawItem += ComboBox_DrawItem;
             leftClickActionComboBox.SelectedIndexChanged += LeftClickActionComboBox_SelectedIndexChanged;

             // 鼠标控制 - 中间单击
             middleClickActionComboBox.Font = new Font("微软雅黑", 12F);
             middleClickActionComboBox.ForeColor = currentDarkMode ? Color.White : Color.FromArgb(51, 51, 51);
             middleClickActionComboBox.BackColor = currentDarkMode ? Color.Black : Color.White;
             middleClickActionComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
             middleClickActionComboBox.DrawMode = DrawMode.OwnerDrawFixed;
             middleClickActionComboBox.Items.AddRange(new object[] { "显示\\隐藏", "内存清理", "打开任务管理器" });
             middleClickActionComboBox.SelectedIndex = 1; // 默认：内存清理
             middleClickActionComboBox.DrawItem += ComboBox_DrawItem;
             middleClickActionComboBox.SelectedIndexChanged += MiddleClickActionComboBox_SelectedIndexChanged;
             
             // 主题设置
             themeComboBox.Font = new Font("微软雅黑", 12F);
             themeComboBox.ForeColor = currentDarkMode ? Color.White : Color.FromArgb(51, 51, 51);
             themeComboBox.BackColor = currentDarkMode ? Color.Black : Color.White;
             themeComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
             themeComboBox.DrawMode = DrawMode.OwnerDrawFixed;
             themeComboBox.Items.AddRange(new object[] { "浅色主题", "深色主题", "自动（跟随系统）" });
             // 不在这里设置SelectedIndex，让LoadDisplaySettings()来设置
             themeComboBox.DrawItem += ComboBox_DrawItem;
             themeComboBox.SelectedIndexChanged += ThemeComboBox_SelectedIndexChanged;
        }

        private void SetupMemoryCleanupControlProperties()
        {
            // 自动内存清理
            autoMemoryCleanupCheckBox.Font = new Font("微软雅黑", 12F);
            autoMemoryCleanupCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            autoMemoryCleanupCheckBox.AutoSize = true;
            autoMemoryCleanupCheckBox.CheckedChanged += AutoMemoryCleanupCheckBox_CheckedChanged;

            // 启用清理间隔
            enableCleanupIntervalCheckBox.Font = new Font("微软雅黑", 10F);
            enableCleanupIntervalCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            enableCleanupIntervalCheckBox.AutoSize = true;
            enableCleanupIntervalCheckBox.Checked = true;
            enableCleanupIntervalCheckBox.CheckedChanged += EnableCleanupIntervalCheckBox_CheckedChanged;

            // 内存清理阈值
            memoryCleanupThresholdNumericUpDown.Font = new Font("微软雅黑", 12F);
            memoryCleanupThresholdNumericUpDown.ForeColor = Color.FromArgb(51, 51, 51);
            memoryCleanupThresholdNumericUpDown.Minimum = 50;
            memoryCleanupThresholdNumericUpDown.Maximum = 95;
            memoryCleanupThresholdNumericUpDown.Value = 90;
            memoryCleanupThresholdNumericUpDown.Width = 80;
            memoryCleanupThresholdNumericUpDown.ValueChanged += MemoryCleanupThresholdNumericUpDown_ValueChanged;

            // 启用内存阈值
            enableMemoryThresholdCheckBox.Font = new Font("微软雅黑", 10F);
            enableMemoryThresholdCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            enableMemoryThresholdCheckBox.AutoSize = true;
            enableMemoryThresholdCheckBox.Checked = true;
            enableMemoryThresholdCheckBox.CheckedChanged += EnableMemoryThresholdCheckBox_CheckedChanged;

            // 深度内存清理
            deepMemoryCleanupCheckBox.Font = new Font("微软雅黑", 12F);
            deepMemoryCleanupCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            deepMemoryCleanupCheckBox.AutoSize = true;
            deepMemoryCleanupCheckBox.Checked = true;
            deepMemoryCleanupCheckBox.CheckedChanged += DeepMemoryCleanupCheckBox_CheckedChanged;

            // 系统缓存清理
            systemCacheCleanupCheckBox.Font = new Font("微软雅黑", 12F);
            systemCacheCleanupCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            systemCacheCleanupCheckBox.AutoSize = true;
            systemCacheCleanupCheckBox.Checked = true;
            systemCacheCleanupCheckBox.CheckedChanged += SystemCacheCleanupCheckBox_CheckedChanged;

            // 进程内存清理
            processMemoryCleanupCheckBox.Font = new Font("微软雅黑", 12F);
            processMemoryCleanupCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            processMemoryCleanupCheckBox.AutoSize = true;
            processMemoryCleanupCheckBox.Checked = true;
            processMemoryCleanupCheckBox.CheckedChanged += ProcessMemoryCleanupCheckBox_CheckedChanged;

            // 清理间隔
            cleanupIntervalNumericUpDown.Font = new Font("微软雅黑", 12F);
            cleanupIntervalNumericUpDown.ForeColor = Color.FromArgb(51, 51, 51);
            cleanupIntervalNumericUpDown.Minimum = 1;
            cleanupIntervalNumericUpDown.Maximum = 80;
            cleanupIntervalNumericUpDown.Value = 30;
            cleanupIntervalNumericUpDown.Width = 80;
            cleanupIntervalNumericUpDown.ValueChanged += CleanupIntervalNumericUpDown_ValueChanged;

            // 显示清理进度
            showCleanupProgressCheckBox.Font = new Font("微软雅黑", 12F);
            showCleanupProgressCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            showCleanupProgressCheckBox.AutoSize = true;
            showCleanupProgressCheckBox.Checked = true;
            showCleanupProgressCheckBox.CheckedChanged += ShowCleanupProgressCheckBox_CheckedChanged;

            // 自动清理冷却时间
            enableAutoCleanupCooldownCheckBox.Font = new Font("微软雅黑", 10F);
            enableAutoCleanupCooldownCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            enableAutoCleanupCooldownCheckBox.AutoSize = true;
            enableAutoCleanupCooldownCheckBox.Checked = true;
            enableAutoCleanupCooldownCheckBox.CheckedChanged += EnableAutoCleanupCooldownCheckBox_CheckedChanged;

            autoCleanupCooldownNumericUpDown.Font = new Font("微软雅黑", 12F);
            autoCleanupCooldownNumericUpDown.ForeColor = Color.FromArgb(51, 51, 51);
            autoCleanupCooldownNumericUpDown.Minimum = 5;
            autoCleanupCooldownNumericUpDown.Maximum = 300;
            autoCleanupCooldownNumericUpDown.Value = 90;
            autoCleanupCooldownNumericUpDown.Width = 80;
            autoCleanupCooldownNumericUpDown.ValueChanged += AutoCleanupCooldownNumericUpDown_ValueChanged;

            // 要清理的内存区域设置
            SetupMemoryRegionCleanupControlProperties();
        }

        private void SetupMemoryRegionCleanupControlProperties()
        {
            // 工作集
            workingSetCleanupCheckBox.Font = new Font("微软雅黑", 10F);
            workingSetCleanupCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            workingSetCleanupCheckBox.AutoSize = true;
            workingSetCleanupCheckBox.CheckedChanged += WorkingSetCleanupCheckBox_CheckedChanged;

            // 系统文件缓存
            systemFileCacheCleanupCheckBox.Font = new Font("微软雅黑", 10F);
            systemFileCacheCleanupCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            systemFileCacheCleanupCheckBox.AutoSize = true;
            systemFileCacheCleanupCheckBox.CheckedChanged += SystemFileCacheCleanupCheckBox_CheckedChanged;

            // 已修改页列表*
            modifiedPageListCleanupCheckBox.Font = new Font("微软雅黑", 10F);
            modifiedPageListCleanupCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            modifiedPageListCleanupCheckBox.AutoSize = true;
            modifiedPageListCleanupCheckBox.CheckedChanged += ModifiedPageListCleanupCheckBox_CheckedChanged;

            // 待机列表*
            standbyListCleanupCheckBox.Font = new Font("微软雅黑", 10F);
            standbyListCleanupCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            standbyListCleanupCheckBox.AutoSize = true;
            standbyListCleanupCheckBox.CheckedChanged += StandbyListCleanupCheckBox_CheckedChanged;

            // 待机列表（无优先级）
            standbyListNoPriorityCleanupCheckBox.Font = new Font("微软雅黑", 10F);
            standbyListNoPriorityCleanupCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            standbyListNoPriorityCleanupCheckBox.AutoSize = true;
            standbyListNoPriorityCleanupCheckBox.CheckedChanged += StandbyListNoPriorityCleanupCheckBox_CheckedChanged;

            // 已修改文件缓存
            modifiedFileCacheCleanupCheckBox.Font = new Font("微软雅黑", 10F);
            modifiedFileCacheCleanupCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            modifiedFileCacheCleanupCheckBox.AutoSize = true;
            modifiedFileCacheCleanupCheckBox.CheckedChanged += ModifiedFileCacheCleanupCheckBox_CheckedChanged;

            // 注册表缓存（Windows 8.1 及以上）
            registryCacheCleanupCheckBox.Font = new Font("微软雅黑", 10F);
            registryCacheCleanupCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            registryCacheCleanupCheckBox.AutoSize = true;
            registryCacheCleanupCheckBox.CheckedChanged += RegistryCacheCleanupCheckBox_CheckedChanged;

            // 合并内存列表（Windows 10 及以上）
            mergedMemoryListCleanupCheckBox.Font = new Font("微软雅黑", 10F);
            mergedMemoryListCleanupCheckBox.ForeColor = Color.FromArgb(51, 51, 51);
            mergedMemoryListCleanupCheckBox.AutoSize = true;
            mergedMemoryListCleanupCheckBox.CheckedChanged += MergedMemoryListCleanupCheckBox_CheckedChanged;
        }

        #region 设置加载方法
        /// <summary>
        /// 加载常规设置
        /// 从注册表读取常规设置的值并更新对应的UI控件
        /// </summary>
        private void LoadGeneralSettings()
        {
            // 直接从注册表读取当前设置状态，确保获取最新值
            try
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\MemGuardian"))
                {
                    if (key != null)
                    {
                        // 窗口始终置顶
                        object? topMostValue = key.GetValue("TopMost");
                        alwaysOnTopCheckBox.Checked = topMostValue != null && Convert.ToBoolean(topMostValue);
                        
                        // 开机自启 - 从Windows启动项注册表读取
                        autoStartCheckBox.Checked = IsAutoStartEnabled();
                        
                        // 最小化启动
                        object? minimizeStartupValue = key.GetValue("MinimizeStartup");
                        minimizeStartupCheckBox.Checked = minimizeStartupValue != null && Convert.ToBoolean(minimizeStartupValue);
                        
                        // 关闭最小化到托盘
                        object? closeToTrayValue = key.GetValue("CloseToTray");
                        closeToTrayCheckBox.Checked = closeToTrayValue != null ? Convert.ToBoolean(closeToTrayValue) : true; // 默认勾选
                        
                        // 手动确认
                        object? manualConfirmValue = key.GetValue("ManualConfirm");
                        manualConfirmCheckBox.Checked = manualConfirmValue != null && Convert.ToBoolean(manualConfirmValue);
                        
                        // 跳过UAC提示
                        object? skipUacPromptValue = key.GetValue("SkipUacPrompt");
                        isLoadingSettings = true; // 设置加载标志，避免触发安全警告
                        skipUacPromptCheckBox.Checked = skipUacPromptValue != null && Convert.ToBoolean(skipUacPromptValue);
                        isLoadingSettings = false; // 重置加载标志
                        
                        // 更新UAC复选框的启用状态
                        UpdateSkipUacPromptCheckBoxEnabled();
                        
                        // 显示内存清理结果气泡
                        object? showMemoryCleanupBubbleValue = key.GetValue("ShowMemoryCleanupBubble");
                        showMemoryCleanupBubbleCheckBox.Checked = showMemoryCleanupBubbleValue != null ? Convert.ToBoolean(showMemoryCleanupBubbleValue) : true;
                        
                        // 开启内存清理声音通知
                        object? enableMemoryCleanupSoundValue = key.GetValue("EnableMemoryCleanupSound");
                        enableMemoryCleanupSoundCheckBox.Checked = enableMemoryCleanupSoundValue != null ? Convert.ToBoolean(enableMemoryCleanupSoundValue) : true;
                        
                         // 鼠标控制设置
                         object? leftClickActionValue = key.GetValue("LeftClickAction");
                         leftClickActionComboBox.SelectedIndex = leftClickActionValue != null ? Math.Max(0, Math.Min(2, Convert.ToInt32(leftClickActionValue))) : 0; // 默认：显示\隐藏
                         
                         object? middleClickActionValue = key.GetValue("MiddleClickAction");
                         middleClickActionComboBox.SelectedIndex = middleClickActionValue != null ? Math.Max(0, Math.Min(2, Convert.ToInt32(middleClickActionValue))) : 1; // 默认：内存清理
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"加载设置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

         /// <summary>
         /// 加载显示设置
         /// 从注册表读取显示设置的值并更新对应的UI控件
         /// </summary>
         private void LoadDisplaySettings()
         {
             try
             {
                 // 优先从主窗口获取当前主题状态，确保同步
                 bool currentDarkMode = isDarkMode;
                 if (mainForm != null)
                 {
                     currentDarkMode = mainForm.IsDarkModeEnabled();
                 }
                 
                 // 根据当前主题状态设置主题选择框
                 if (currentDarkMode)
                 {
                     themeComboBox.SelectedIndex = 1; // 深色主题
                 }
                 else
                 {
                     themeComboBox.SelectedIndex = 0; // 浅色主题
                 }
                 
                 // 如果注册表中有"自动"设置，则使用注册表的值
                 using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\MemGuardian"))
                 {
                     if (key != null)
                     {
                         object? themeModeValue = key.GetValue("ThemeMode");
                         if (themeModeValue != null)
                         {
                             int themeMode = Convert.ToInt32(themeModeValue);
                             if (themeMode == 2) // 自动（跟随系统）
                             {
                                 themeComboBox.SelectedIndex = 2;
                             }
                         }
                         
                         // 加载托盘图标颜色设置
                         LoadTrayIconColorSettings(key);
                     }
                 }
             }
             catch (Exception ex)
             {
                 MessageBox.Show(this, $"加载显示设置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
         }

         private void LoadMemoryCleanupSettings()
         {
             // 从注册表读取内存清理设置
             try
             {
                 using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\MemGuardian"))
                 {
                     if (key != null)
                     {
                        // 自动内存清理
                        object? autoMemoryCleanupValue = key.GetValue("AutoMemoryCleanup");
                        autoMemoryCleanupCheckBox.Checked = autoMemoryCleanupValue != null && Convert.ToBoolean(autoMemoryCleanupValue);

                        // 内存清理阈值
                        object? memoryCleanupThresholdValue = key.GetValue("MemoryCleanupThreshold");
                        if (memoryCleanupThresholdValue != null)
                        {
                            memoryCleanupThresholdNumericUpDown.Value = Math.Max(50, Math.Min(95, Convert.ToInt32(memoryCleanupThresholdValue)));
                        }

                        // 深度内存清理
                        object? deepMemoryCleanupValue = key.GetValue("DeepMemoryCleanup");
                        deepMemoryCleanupCheckBox.Checked = deepMemoryCleanupValue == null || Convert.ToBoolean(deepMemoryCleanupValue);

                        // 系统缓存清理
                        object? systemCacheCleanupValue = key.GetValue("SystemCacheCleanup");
                        systemCacheCleanupCheckBox.Checked = systemCacheCleanupValue == null || Convert.ToBoolean(systemCacheCleanupValue);

                        // 进程内存清理
                        object? processMemoryCleanupValue = key.GetValue("ProcessMemoryCleanup");
                        processMemoryCleanupCheckBox.Checked = processMemoryCleanupValue == null || Convert.ToBoolean(processMemoryCleanupValue);

                        // 清理间隔
                        object? cleanupIntervalValue = key.GetValue("CleanupInterval");
                        if (cleanupIntervalValue != null)
                        {
                            cleanupIntervalNumericUpDown.Value = Math.Max(1, Math.Min(80, Convert.ToInt32(cleanupIntervalValue)));
                        }

                        // 显示清理进度
                        object? showCleanupProgressValue = key.GetValue("ShowCleanupProgress");
                        showCleanupProgressCheckBox.Checked = showCleanupProgressValue == null || Convert.ToBoolean(showCleanupProgressValue);

                        // 启用清理间隔
                        object? enableCleanupIntervalValue = key.GetValue("EnableCleanupInterval");
                        enableCleanupIntervalCheckBox.Checked = enableCleanupIntervalValue != null && Convert.ToBoolean(enableCleanupIntervalValue);

                        // 启用内存阈值
                        object? enableMemoryThresholdValue = key.GetValue("EnableMemoryThreshold");
                        enableMemoryThresholdCheckBox.Checked = enableMemoryThresholdValue == null || Convert.ToBoolean(enableMemoryThresholdValue);

                        // 自动清理冷却时间
                        object? autoCleanupCooldownValue = key.GetValue("AutoCleanupCooldown");
                        if (autoCleanupCooldownValue != null)
                        {
                            autoCleanupCooldownNumericUpDown.Value = Math.Max(5, Math.Min(300, Convert.ToInt32(autoCleanupCooldownValue)));
                        }

                        // 启用自动清理冷却时间
                        object? enableAutoCleanupCooldownValue = key.GetValue("EnableAutoCleanupCooldown");
                        enableAutoCleanupCooldownCheckBox.Checked = enableAutoCleanupCooldownValue == null || Convert.ToBoolean(enableAutoCleanupCooldownValue);

                        // 要清理的内存区域设置
                        LoadMemoryRegionCleanupSettings(key);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"加载内存清理设置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadMemoryRegionCleanupSettings(RegistryKey key)
        {
            // 工作集
            object? workingSetValue = key.GetValue("WorkingSetCleanup");
            workingSetCleanupCheckBox.Checked = workingSetValue == null || Convert.ToBoolean(workingSetValue);

            // 系统文件缓存
            object? systemFileCacheValue = key.GetValue("SystemFileCacheCleanup");
            systemFileCacheCleanupCheckBox.Checked = systemFileCacheValue == null || Convert.ToBoolean(systemFileCacheValue);

            // 已修改页列表*
            object? modifiedPageListValue = key.GetValue("ModifiedPageListCleanup");
            modifiedPageListCleanupCheckBox.Checked = modifiedPageListValue != null && Convert.ToBoolean(modifiedPageListValue);

            // 待机列表*
            object? standbyListValue = key.GetValue("StandbyListCleanup");
            standbyListCleanupCheckBox.Checked = standbyListValue != null && Convert.ToBoolean(standbyListValue);

            // 待机列表（无优先级）
            object? standbyListNoPriorityValue = key.GetValue("StandbyListNoPriorityCleanup");
            standbyListNoPriorityCleanupCheckBox.Checked = standbyListNoPriorityValue == null || Convert.ToBoolean(standbyListNoPriorityValue);

            // 已修改文件缓存
            object? modifiedFileCacheValue = key.GetValue("ModifiedFileCacheCleanup");
            modifiedFileCacheCleanupCheckBox.Checked = modifiedFileCacheValue == null || Convert.ToBoolean(modifiedFileCacheValue);

            // 注册表缓存（Windows 8.1 及以上）
            object? registryCacheValue = key.GetValue("RegistryCacheCleanup");
            registryCacheCleanupCheckBox.Checked = registryCacheValue == null || Convert.ToBoolean(registryCacheValue);

            // 合并内存列表（Windows 10 及以上）
            object? mergedMemoryListValue = key.GetValue("MergedMemoryListCleanup");
            mergedMemoryListCleanupCheckBox.Checked = mergedMemoryListValue == null || Convert.ToBoolean(mergedMemoryListValue);
        }

         /// <summary>
         /// 刷新当前显示的分类设置
         /// 当设置值发生变化时，重新加载当前选中分类的所有设置项
         /// </summary>
         /// <remarks>
         /// 此方法用于在设置值被外部修改后同步UI显示
         /// 根据当前选中的分类索引，调用相应的设置显示方法
         /// </remarks>
         public void RefreshSettings()
         {
             // 刷新当前显示的分类设置
             if (categoryListBox.SelectedIndex >= 0)
             {
                 string selectedCategory = categoryListBox.Items[categoryListBox.SelectedIndex].ToString() ?? "";
                 if (selectedCategory == "常规设置")
                 {
                     LoadGeneralSettings();
                 }
                 else if (selectedCategory == "显示设置")
                 {
                     LoadDisplaySettings();
                 }
                 else if (selectedCategory == "内存清理")
                 {
                     LoadMemoryCleanupSettings();
                 }
             }
         }

        /// <summary>
        /// 刷新清理间隔设置UI
        /// 当托盘菜单中的清理间隔设置改变时调用，确保设置窗体显示最新的间隔值
        /// </summary>
        /// <remarks>
        /// 此方法从注册表读取最新的清理间隔设置，并更新对应的UI控件
        /// 包括启用状态和具体的间隔值，确保UI与实际的设置值保持同步
        /// </remarks>
        public void RefreshCleanupIntervalSettings()
        {
            try
            {
                // 如果当前显示的是内存清理设置，则刷新UI
                if (categoryListBox.SelectedIndex >= 0)
                {
                    string selectedCategory = categoryListBox.Items[categoryListBox.SelectedIndex].ToString() ?? "";
                    if (selectedCategory == "内存清理")
                    {
                        // 从注册表读取最新的清理间隔设置
                        using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\MemGuardian"))
                        {
                            if (key != null)
                            {
                                // 读取AutoCleanupInterval（托盘菜单设置）
                                object? autoCleanupIntervalValue = key.GetValue("AutoCleanupInterval");
                                int autoCleanupInterval = autoCleanupIntervalValue != null ? Convert.ToInt32(autoCleanupIntervalValue) : -1;

                                // 更新UI控件
                                if (autoCleanupInterval == -1)
                                {
                                    // 如果托盘菜单选择禁用，则取消勾选启用清理间隔
                                    enableCleanupIntervalCheckBox.Checked = false;
                                }
                                else
                                {
                                    // 如果托盘菜单选择了具体间隔，则勾选启用清理间隔并设置间隔值
                                    enableCleanupIntervalCheckBox.Checked = true;
                                    cleanupIntervalNumericUpDown.Value = Math.Max(1, Math.Min(80, autoCleanupInterval));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // 静默处理清理间隔设置UI刷新异常
            }
        }

        /// <summary>
        /// 刷新内存阈值设置UI
        /// 当托盘菜单中的清理界限设置改变时调用，确保设置窗体显示最新的阈值设置
        /// </summary>
        /// <remarks>
        /// 此方法从注册表读取最新的内存阈值设置，并更新对应的UI控件
        /// 包括启用状态和具体的阈值百分比，确保UI与实际的设置值保持同步
        /// </remarks>
        public void RefreshMemoryThresholdSettings()
        {
            try
            {
                // 如果当前显示的是内存清理设置，则刷新UI
                if (categoryListBox.SelectedIndex >= 0)
                {
                    string selectedCategory = categoryListBox.Items[categoryListBox.SelectedIndex].ToString() ?? "";
                    if (selectedCategory == "内存清理")
                    {
                        // 从注册表读取最新的清理界限设置
                        using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\MemGuardian"))
                        {
                            if (key != null)
                            {
                                // 读取AutoCleanupThreshold（托盘菜单设置）
                                object? autoCleanupThresholdValue = key.GetValue("AutoCleanupThreshold");
                                int autoCleanupThreshold = autoCleanupThresholdValue != null ? Convert.ToInt32(autoCleanupThresholdValue) : -1;

                                // 更新UI控件
                                if (autoCleanupThreshold == -1)
                                {
                                    // 如果托盘菜单选择禁用，则取消勾选启用内存阈值
                                    enableMemoryThresholdCheckBox.Checked = false;
                                }
                                else
                                {
                                    // 如果托盘菜单选择了具体阈值，则勾选启用内存阈值并设置阈值值
                                    enableMemoryThresholdCheckBox.Checked = true;
                                    memoryCleanupThresholdNumericUpDown.Value = Math.Max(50, Math.Min(95, autoCleanupThreshold));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // 静默处理内存阈值设置UI刷新异常
            }
        }

        private bool IsAutoStartEnabled()
        {
            try
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"))
                {
                    if (key != null)
                    {
                        string? value = key.GetValue("MemGuardian") as string;
                        return !string.IsNullOrEmpty(value);
                    }
                }
            }
            catch
            {
                // 忽略注册表访问错误
            }
            return false;
        }

        #region 事件处理方法
        /// <summary>
        /// 窗口置顶复选框状态改变事件处理
        /// 当用户修改窗口置顶设置时，立即同步到主窗体
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void AlwaysOnTopCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            // 同步到主窗体菜单
            var mainForm = this.Owner as Form1;
            if (mainForm != null)
            {
                mainForm.SetAlwaysOnTopStatus(alwaysOnTopCheckBox.Checked);
                
                // 同时更新设置窗口的置顶状态
                this.TopMost = alwaysOnTopCheckBox.Checked;
            }
        }

        /// <summary>
        /// 自动启动复选框状态改变事件处理
        /// 当用户修改自动启动设置时，立即保存到注册表
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void AutoStartCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            // 同步到主窗体菜单
            var mainForm = this.Owner as Form1;
            if (mainForm != null)
            {
                mainForm.SetAutoStartStatus(autoStartCheckBox.Checked);
            }
        }

        private void MinimizeStartupCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            // 同步到主窗体菜单
            var mainForm = this.Owner as Form1;
            if (mainForm != null)
            {
                mainForm.SetMinimizeStartupStatus(minimizeStartupCheckBox.Checked);
            }
        }

        private void CloseToTrayCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            // 保存到注册表
            try
            {
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                {
                    key?.SetValue("CloseToTray", closeToTrayCheckBox.Checked);
                }
                
                // 通知主窗体刷新关闭到托盘设置
                var mainForm = this.Owner as Form1;
                if (mainForm != null)
                {
                    mainForm.RefreshCloseToTraySettings();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"保存设置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ManualConfirmCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            // 同步到主窗体菜单
            var mainForm = this.Owner as Form1;
            if (mainForm != null)
            {
                mainForm.SetManualConfirmStatus(manualConfirmCheckBox.Checked);
            }
        }

        private void SkipUacPromptCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            try
            {
                // 如果用户勾选了复选框且不是加载状态，显示安全警告
                if (skipUacPromptCheckBox.Checked && !isLoadingSettings)
                {
                    var result = MessageBox.Show(this, 
                        "安全警告！不建议在非安全位置（如 Program Files）运行时启用此选项。确实要继续吗？", 
                        "安全警告", 
                        MessageBoxButtons.YesNo, 
                        MessageBoxIcon.Warning);
                    
                    if (result != DialogResult.Yes)
                    {
                        // 用户选择"否"，取消勾选
                        skipUacPromptCheckBox.Checked = false;
                        return;
                    }
                }
                
                // 保存到注册表
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                {
                    key?.SetValue("SkipUacPrompt", skipUacPromptCheckBox.Checked);
                }
                
                // 通知主窗体刷新UAC跳过设置
                var mainForm = this.Owner as Form1;
                if (mainForm != null)
                {
                    mainForm.SetSkipUacPromptStatus(skipUacPromptCheckBox.Checked);
                }
                
                // 更新UAC复选框的启用状态
                UpdateSkipUacPromptCheckBoxEnabled();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"保存设置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ShowMemoryCleanupBubbleCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            // 保存到注册表
            try
            {
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                {
                    key?.SetValue("ShowMemoryCleanupBubble", showMemoryCleanupBubbleCheckBox.Checked);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"保存设置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void EnableMemoryCleanupSoundCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            // 保存到注册表
            try
            {
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                {
                    key?.SetValue("EnableMemoryCleanupSound", enableMemoryCleanupSoundCheckBox.Checked);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"保存设置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LeftClickActionComboBox_SelectedIndexChanged(object? sender, EventArgs e)
        {
            // 保存到注册表
            try
            {
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                {
                    key?.SetValue("LeftClickAction", leftClickActionComboBox.SelectedIndex);
                }
                
                // 通知主窗体刷新鼠标控制设置
                var mainForm = this.Owner as Form1;
                if (mainForm != null)
                {
                    mainForm.RefreshMouseControlSettings();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"保存设置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

         private void MiddleClickActionComboBox_SelectedIndexChanged(object? sender, EventArgs e)
         {
             // 保存到注册表
             try
             {
                 using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                 {
                     key?.SetValue("MiddleClickAction", middleClickActionComboBox.SelectedIndex);
                 }
                 
                 // 通知主窗体刷新鼠标控制设置
                 var mainForm = this.Owner as Form1;
                 if (mainForm != null)
                 {
                     mainForm.RefreshMouseControlSettings();
                 }
             }
             catch (Exception ex)
             {
                 MessageBox.Show(this, $"保存设置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
         }
         
         /// <summary>
         /// 主题下拉框选择改变事件处理
         /// 当用户修改主题设置时，立即应用新的主题并保存到注册表
         /// </summary>
         /// <param name="sender">事件发送者</param>
         /// <param name="e">事件参数</param>
         private void ThemeComboBox_SelectedIndexChanged(object? sender, EventArgs e)
         {
             try
             {
                 // 保存主题设置到注册表
                 using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                 {
                     key?.SetValue("ThemeMode", themeComboBox.SelectedIndex);
                 }
                 
                 // 应用主题设置
                 ApplyThemeSetting();
                 
                 // 通知主窗体更新主题
                 var mainForm = this.Owner as Form1;
                 if (mainForm != null)
                 {
                     // 通知主窗体刷新夜间模式状态
                     mainForm.RefreshDarkModeFromSettings();
                 }
             }
             catch (Exception ex)
             {
                 MessageBox.Show(this, $"保存主题设置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
         }

        // 内存清理设置事件处理方法
        private void AutoMemoryCleanupCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            // 保存到注册表
            try
            {
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                {
                    key?.SetValue("AutoMemoryCleanup", autoMemoryCleanupCheckBox.Checked);
                }
            }
            catch
            {
                // 静默处理错误
            }
        }

        private void MemoryCleanupThresholdNumericUpDown_ValueChanged(object? sender, EventArgs e)
        {
            // 保存到注册表
            try
            {
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                {
                    // 保存内存阈值值
                    int threshold = (int)memoryCleanupThresholdNumericUpDown.Value;
                    key?.SetValue("MemoryCleanupThreshold", threshold);
                    
                    // 如果启用了内存阈值，同时保存启用状态和同步AutoCleanupThreshold
                    if (enableMemoryThresholdCheckBox.Checked)
                    {
                        key?.SetValue("EnableMemoryThreshold", true);
                        key?.SetValue("AutoCleanupThreshold", threshold);
                    }
                }
                
                // 通知主窗体刷新托盘菜单
                var mainForm = this.Owner as Form1;
                if (mainForm != null)
                {
                    mainForm.RefreshTrayMenu();
                }
            }
            catch
            {
                // 静默处理错误
            }
        }

        private void DeepMemoryCleanupCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            // 保存到注册表
            try
            {
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                {
                    key?.SetValue("DeepMemoryCleanup", deepMemoryCleanupCheckBox.Checked);
                }
            }
            catch
            {
                // 静默处理错误
            }
        }

        private void SystemCacheCleanupCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            // 保存到注册表
            try
            {
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                {
                    key?.SetValue("SystemCacheCleanup", systemCacheCleanupCheckBox.Checked);
                }
            }
            catch
            {
                // 静默处理错误
            }
        }

        private void ProcessMemoryCleanupCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            // 保存到注册表
            try
            {
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                {
                    key?.SetValue("ProcessMemoryCleanup", processMemoryCleanupCheckBox.Checked);
                }
            }
            catch
            {
                // 静默处理错误
            }
        }

        private void CleanupIntervalNumericUpDown_ValueChanged(object? sender, EventArgs e)
        {
            // 保存到注册表
            try
            {
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                {
                    // 保存清理间隔值
                    int interval = (int)cleanupIntervalNumericUpDown.Value;
                    key?.SetValue("CleanupInterval", interval);
                    
                    // 如果启用了清理间隔，同时保存启用状态和同步AutoCleanupInterval
                    if (enableCleanupIntervalCheckBox.Checked)
                    {
                        key?.SetValue("EnableCleanupInterval", true);
                        key?.SetValue("AutoCleanupInterval", interval);
                    }
                }
                
                // 通知主窗体刷新托盘菜单
                var mainForm = this.Owner as Form1;
                if (mainForm != null)
                {
                    mainForm.RefreshTrayMenu();
                }
            }
            catch
            {
                // 静默处理错误
            }
        }

        private void ShowCleanupProgressCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            // 保存到注册表
            try
            {
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                {
                    key?.SetValue("ShowCleanupProgress", showCleanupProgressCheckBox.Checked);
                }
            }
            catch
            {
                // 静默处理错误
            }
        }

        private void EnableCleanupIntervalCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            // 保存到注册表
            try
            {
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                {
                    key?.SetValue("EnableCleanupInterval", enableCleanupIntervalCheckBox.Checked);
                    
                    // 同步更新AutoCleanupInterval以保持托盘菜单同步
                    if (enableCleanupIntervalCheckBox.Checked)
                    {
                        // 如果启用，使用当前设置的间隔值
                        int interval = (int)cleanupIntervalNumericUpDown.Value;
                        key?.SetValue("AutoCleanupInterval", interval);
                    }
                    else
                    {
                        // 如果禁用，设置为-1
                        key?.SetValue("AutoCleanupInterval", -1);
                    }
                }
                
                // 通知主窗体刷新托盘菜单
                var mainForm = this.Owner as Form1;
                if (mainForm != null)
                {
                    mainForm.RefreshTrayMenu();
                }
            }
            catch
            {
                // 静默处理错误
            }
        }

        private void EnableMemoryThresholdCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            // 保存到注册表
            try
            {
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                {
                    key?.SetValue("EnableMemoryThreshold", enableMemoryThresholdCheckBox.Checked);
                    
                    // 同步更新AutoCleanupThreshold以保持托盘菜单同步
                    if (enableMemoryThresholdCheckBox.Checked)
                    {
                        // 如果启用，使用当前设置的阈值值
                        int threshold = (int)memoryCleanupThresholdNumericUpDown.Value;
                        key?.SetValue("AutoCleanupThreshold", threshold);
                    }
                    else
                    {
                        // 如果禁用，设置为-1
                        key?.SetValue("AutoCleanupThreshold", -1);
                    }
                }
                
                // 通知主窗体刷新托盘菜单
                var mainForm = this.Owner as Form1;
                if (mainForm != null)
                {
                    mainForm.RefreshTrayMenu();
                }
            }
            catch
            {
                // 静默处理错误
            }
        }

        // 要清理的内存区域事件处理方法
        private void WorkingSetCleanupCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            SaveMemoryRegionSetting("WorkingSetCleanup", workingSetCleanupCheckBox.Checked);
        }

        private void SystemFileCacheCleanupCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            SaveMemoryRegionSetting("SystemFileCacheCleanup", systemFileCacheCleanupCheckBox.Checked);
        }

        private void ModifiedPageListCleanupCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            SaveMemoryRegionSetting("ModifiedPageListCleanup", modifiedPageListCleanupCheckBox.Checked);
        }

        private void StandbyListCleanupCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            SaveMemoryRegionSetting("StandbyListCleanup", standbyListCleanupCheckBox.Checked);
        }

        private void StandbyListNoPriorityCleanupCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            SaveMemoryRegionSetting("StandbyListNoPriorityCleanup", standbyListNoPriorityCleanupCheckBox.Checked);
        }

        private void ModifiedFileCacheCleanupCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            SaveMemoryRegionSetting("ModifiedFileCacheCleanup", modifiedFileCacheCleanupCheckBox.Checked);
        }

        private void RegistryCacheCleanupCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            SaveMemoryRegionSetting("RegistryCacheCleanup", registryCacheCleanupCheckBox.Checked);
        }

        private void MergedMemoryListCleanupCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            SaveMemoryRegionSetting("MergedMemoryListCleanup", mergedMemoryListCleanupCheckBox.Checked);
        }

        private void SaveMemoryRegionSetting(string settingName, bool value)
        {
            try
            {
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                {
                    key?.SetValue(settingName, value);
                }
            }
            catch
            {
                // 静默处理错误
            }
        }

        private void CategoryListBox_DrawItem(object? sender, DrawItemEventArgs e)
        {
            if (e.Index < 0) return;

            var listBox = sender as ListBox;
            if (listBox == null) return;

            // 获取项目文本
            string text = listBox.Items[e.Index].ToString() ?? "";

            // 设置绘制参数
            e.DrawBackground();

            // 判断是否选中
            bool isSelected = (e.State & DrawItemState.Selected) == DrawItemState.Selected;

            // 根据夜间模式状态设置颜色
            Color backColor, textColor;
            
            if (isDarkMode)
            {
                // 夜间模式配色
                backColor = isSelected ? Color.FromArgb(0, 120, 215) : Color.FromArgb(23, 23, 23);
                textColor = Color.White; // 夜间模式下文字始终为白色
            }
            else
            {
                // 浅色模式配色
                backColor = isSelected ? Color.FromArgb(76, 175, 80) : Color.White;
                textColor = isSelected ? Color.White : Color.FromArgb(51, 51, 51);
            }

            // 绘制背景
            using (SolidBrush backBrush = new SolidBrush(backColor))
            {
                e.Graphics.FillRectangle(backBrush, e.Bounds);
            }

            // 绘制文本
            using (SolidBrush textBrush = new SolidBrush(textColor))
            {
                StringFormat sf = new StringFormat();
                sf.Alignment = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;
                if (e.Font != null)
                {
                    e.Graphics.DrawString(text, e.Font, textBrush, e.Bounds, sf);
                }
            }

            // 绘制焦点矩形
            e.DrawFocusRectangle();
        }

        // CreateGroupBox方法已删除，因为未被使用

        private Label CreateCategoryLabel(string title, Point location)
        {
            var label = new Label();
            label.Text = title;
            label.Font = new Font("微软雅黑", 9F);
            // 分类标题保持蓝色，不受主题影响
            label.ForeColor = Color.FromArgb(33, 150, 243);
            label.AutoSize = true;
            label.Location = location;
            label.Height = 24;

            return label;
        }

        private Panel CreateSettingItemPanel(string labelText, CheckBox checkBox, int yPosition)
        {
            var panel = new Panel();
            // 使用相对宽度，适应不同分辨率
            panel.Size = new Size(rightPanel.Width - 50, 40);
            panel.Location = new Point(25, yPosition);
            panel.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;

            // 复选框 - 放在最前面
            checkBox.Text = labelText;
            checkBox.Font = new Font("微软雅黑", 10F);
            // 根据当前主题设置字体颜色
            checkBox.ForeColor = isDarkMode ? Color.White : Color.FromArgb(51, 51, 51);
            checkBox.AutoSize = true;
            checkBox.Location = new Point(10, 10);
            checkBox.Size = new Size(20, 20);
            checkBox.FlatStyle = FlatStyle.Flat;
            checkBox.FlatAppearance.BorderSize = 1;
            checkBox.FlatAppearance.BorderColor = Color.FromArgb(33, 150, 243);
            // 移除背景色变化事件
            panel.Controls.Add(checkBox);

            return panel;
        }

        // CreateSettingItemPanel(NumericUpDown)方法已删除，因为未被使用

        private Panel CreateSettingItemPanel(string labelText, CheckBox checkBox, NumericUpDown numericUpDown, int yPosition)
        {
            var panel = new Panel();
            // 使用相对宽度，适应不同分辨率
            panel.Size = new Size(rightPanel.Width - 50, 40);
            panel.Location = new Point(25, yPosition);
            panel.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;

            // 复选框
            checkBox.Text = labelText;
            checkBox.Font = new Font("微软雅黑", 10F);
            // 根据当前主题设置字体颜色
            checkBox.ForeColor = isDarkMode ? Color.White : Color.FromArgb(51, 51, 51);
            checkBox.AutoSize = true;
            checkBox.Location = new Point(10, 10);
            checkBox.Size = new Size(20, 20);
            checkBox.FlatStyle = FlatStyle.Flat;
            checkBox.FlatAppearance.BorderSize = 1;
            checkBox.FlatAppearance.BorderColor = Color.FromArgb(33, 150, 243);
            panel.Controls.Add(checkBox);

            // 数值输入框 - 使用相对位置
            numericUpDown.Location = new Point(panel.Width - 90, 8);
            numericUpDown.Size = new Size(80, 24);
            numericUpDown.Anchor = AnchorStyles.Top | AnchorStyles.Right;
            // 设置字体大小
            numericUpDown.Font = new Font("微软雅黑", 9F);
            panel.Controls.Add(numericUpDown);

            return panel;
        }

        // 以下辅助方法已删除，因为未被使用：
        // CreateSliderSettingPanel, CreateTransparencySliderPanel, CreateNumericSettingPanel

        private Panel CreateComboBoxSettingPanel(string labelText, ComboBox comboBox, int yPosition)
        {
            var panel = new Panel();
            // 使用相对宽度，适应不同分辨率
            panel.Size = new Size(rightPanel.Width - 40, 40);
            panel.Location = new Point(20, yPosition);
            panel.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;

            // 标签
            var label = new Label();
            label.Text = labelText;
            label.Font = new Font("微软雅黑", 10F);
            // 根据当前主题设置字体颜色
            label.ForeColor = isDarkMode ? Color.White : Color.FromArgb(51, 51, 51);
            label.AutoSize = true;
            label.Location = new Point(0, 6);
            panel.Controls.Add(label);

            // 下拉框 - 使用相对位置
            comboBox.Font = new Font("微软雅黑", 10F);
            comboBox.Location = new Point(120, 2);
            comboBox.Size = new Size(Math.Min(200, panel.Width - 130), 26);
            comboBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
            comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
            comboBox.DrawMode = DrawMode.OwnerDrawFixed;
            // 根据当前主题设置颜色
            comboBox.BackColor = isDarkMode ? Color.Black : Color.White;
            comboBox.ForeColor = isDarkMode ? Color.White : Color.Black;
            comboBox.DrawItem += ComboBox_DrawItem;
            panel.Controls.Add(comboBox);

            return panel;
        }

        // ResetDefaultSettingsButton_Click和ResetUILayoutButton_Click方法已删除，
        // 因为对应的控件字段已被删除

        /// <summary>
        /// 加载设置窗体初始状态
        /// 设置默认选中的分类，实际的设置值加载在ShowGeneralSettings方法中进行
        /// </summary>
        /// <remarks>
        /// 此方法只负责设置窗体的初始状态，不加载具体的设置值
        /// 因为此时控件可能还未完全初始化，具体的设置加载在分类切换时进行
        /// </remarks>
        private void LoadSettings()
        {
            try
            {
                // 默认选中第一个分类（常规设置）
                categoryListBox.SelectedIndex = 0;

                // 不在这里加载默认设置，因为控件还没有初始化
                // 在ShowGeneralSettings中加载
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"加载设置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        /// <summary>
        /// 初始化所有控件（不添加到界面，只创建控件对象）
        /// </summary>
        private void InitializeAllControls()
        {
            // 初始化常规设置控件
            InitializeGeneralSettingsControls();
            
            // 初始化内存清理控件
            InitializeMemoryCleanupControls();
            
            // 初始化内存清理区域控件
            SetupMemoryRegionCleanupControlProperties();
        }

        private void LoadDefaultSettings()
        {
            try
            {
                // 一、默认勾选启用的复选框设置项（只设置已创建的控件）
                // 1、在内存清理前手动确认
                if (manualConfirmCheckBox != null)
                    manualConfirmCheckBox.Checked = true;
                
                // 1.1、跳过UAC提示（默认不勾选，保持安全性）
                if (skipUacPromptCheckBox != null)
                {
                    isLoadingSettings = true; // 设置加载标志，避免触发安全警告
                    skipUacPromptCheckBox.Checked = false;
                    isLoadingSettings = false; // 重置加载标志
                }
                
                // 2、显示内存清理结果气泡
                if (showMemoryCleanupBubbleCheckBox != null)
                    showMemoryCleanupBubbleCheckBox.Checked = true;
                
                // 3、开启内存清理声音通知
                if (enableMemoryCleanupSoundCheckBox != null)
                    enableMemoryCleanupSoundCheckBox.Checked = true;
                
                // 4、自动清理冷却时间（秒）
                if (enableAutoCleanupCooldownCheckBox != null)
                    enableAutoCleanupCooldownCheckBox.Checked = true;
                
                // 5、工作集
                if (workingSetCleanupCheckBox != null)
                    workingSetCleanupCheckBox.Checked = true;
                
                // 6、系统文件缓存
                if (systemFileCacheCleanupCheckBox != null)
                    systemFileCacheCleanupCheckBox.Checked = true;
                
                // 7、待机列表（无优先级）
                if (standbyListNoPriorityCleanupCheckBox != null)
                    standbyListNoPriorityCleanupCheckBox.Checked = true;
                
                // 8、已修改文件缓存
                if (modifiedFileCacheCleanupCheckBox != null)
                    modifiedFileCacheCleanupCheckBox.Checked = true;
                
                // 9、注册表缓存（Windows 8.1 及以上）
                if (registryCacheCleanupCheckBox != null)
                    registryCacheCleanupCheckBox.Checked = true;
                
                // 10、合并内存列表（Windows 10 及以上）
                if (mergedMemoryListCleanupCheckBox != null)
                    mergedMemoryListCleanupCheckBox.Checked = true;

                // 11、关闭最小化到托盘默认勾选
                if (closeToTrayCheckBox != null)
                    closeToTrayCheckBox.Checked = true;
                
                // 12、其他复选框都为不勾选（不启用）
                if (autoStartCheckBox != null)
                    autoStartCheckBox.Checked = false;
                if (alwaysOnTopCheckBox != null)
                    alwaysOnTopCheckBox.Checked = false;
                if (minimizeStartupCheckBox != null)
                    minimizeStartupCheckBox.Checked = false;
                if (autoMemoryCleanupCheckBox != null)
                    autoMemoryCleanupCheckBox.Checked = false;
                if (enableCleanupIntervalCheckBox != null)
                    enableCleanupIntervalCheckBox.Checked = false;
                if (enableMemoryThresholdCheckBox != null)
                    enableMemoryThresholdCheckBox.Checked = false;
                if (deepMemoryCleanupCheckBox != null)
                    deepMemoryCleanupCheckBox.Checked = false;
                if (systemCacheCleanupCheckBox != null)
                    systemCacheCleanupCheckBox.Checked = false;
                if (processMemoryCleanupCheckBox != null)
                    processMemoryCleanupCheckBox.Checked = false;
                if (showCleanupProgressCheckBox != null)
                    showCleanupProgressCheckBox.Checked = false;
                if (modifiedPageListCleanupCheckBox != null)
                    modifiedPageListCleanupCheckBox.Checked = false;
                if (standbyListCleanupCheckBox != null)
                    standbyListCleanupCheckBox.Checked = false;
                
                // 二、默认值设置项
                // 1、左键单击默认值：显示\隐藏
                if (leftClickActionComboBox != null)
                    leftClickActionComboBox.SelectedIndex = 0;
                
                // 2、中间单击默认值：内存清理
                if (middleClickActionComboBox != null)
                    middleClickActionComboBox.SelectedIndex = 1;
                
                // 3、主题默认值：浅色主题
                if (themeComboBox != null)
                    themeComboBox.SelectedIndex = 0;
                
                // 4、自动清理间隔（分钟）默认值：30
                if (cleanupIntervalNumericUpDown != null)
                    cleanupIntervalNumericUpDown.Value = 30;
                
                // 5、重置托盘图标颜色设置为默认值
                ResetTrayIconColorsToDefault();
                
                // 5、内存使用率超过时自动清理（%）默认值：80
                if (memoryCleanupThresholdNumericUpDown != null)
                    memoryCleanupThresholdNumericUpDown.Value = 80;
                
                // 6、自动清理冷却时间（秒）默认值：90
                if (autoCleanupCooldownNumericUpDown != null)
                    autoCleanupCooldownNumericUpDown.Value = 90;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"设置默认值失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ResetButton_Click(object? sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show(this, "确定要重置所有设置为默认值吗？", "确认重置",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    // 记录当前选中的分类
                    int currentSelectedIndex = categoryListBox.SelectedIndex;
                    string currentCategory = currentSelectedIndex >= 0 ? categoryListBox.Items[currentSelectedIndex].ToString() : "";
                    
                    // 初始化所有控件（不显示，只创建控件对象）
                    InitializeAllControls();
                    
                    // 恢复当前选中的分类显示并设置默认值
                    if (!string.IsNullOrEmpty(currentCategory))
                    {
                        switch (currentCategory)
                        {
                            case "常规设置":
                                ShowProgramBehaviorSettings();
                                LoadDefaultSettings();
                                break;
                            case "显示设置":
                                ShowInteractionControlSettings();
                                LoadDefaultSettings();
                                break;
                            case "内存管理":
                                ShowMemoryManagementSettings();
                                LoadDefaultSettings();
                                break;
                            case "通知反馈":
                                ShowNotificationFeedbackSettings();
                                LoadDefaultSettings();
                                break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"重置设置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void CloseButton_Click(object? sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        /// <summary>
        /// 窗体大小调整事件处理
        /// 当窗体大小改变时，重新调整控件布局以适应新的窗体尺寸
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void SettingsForm_Resize(object? sender, EventArgs e)
        {
            // 刷新当前显示的分类设置，让控件重新适应新的窗体大小
            if (categoryListBox.SelectedIndex >= 0)
            {
                string selectedCategory = categoryListBox.Items[categoryListBox.SelectedIndex].ToString() ?? "";
                switch (selectedCategory)
                {
                    case "常规设置":
                        ShowProgramBehaviorSettings();
                        break;
                    case "显示设置":
                        ShowInteractionControlSettings();
                        break;
                    case "内存管理":
                        ShowMemoryManagementSettings();
                        break;
                    case "通知反馈":
                        ShowNotificationFeedbackSettings();
                        break;
                }
            }
        }

        // 自动清理冷却时间相关事件处理方法
        private void EnableAutoCleanupCooldownCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            // 保存到注册表
            try
            {
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                {
                    key?.SetValue("EnableAutoCleanupCooldown", enableAutoCleanupCooldownCheckBox.Checked);
                }
            }
            catch
            {
                // 静默处理错误
            }
        }

        private void AutoCleanupCooldownNumericUpDown_ValueChanged(object? sender, EventArgs e)
        {
            // 保存到注册表
            try
            {
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                {
                    int cooldown = (int)autoCleanupCooldownNumericUpDown.Value;
                    key?.SetValue("AutoCleanupCooldown", cooldown);
                }
            }
            catch
            {
                // 静默处理错误
            }
        }
        #endregion

        #region 夜间模式支持
         /// <summary>
         /// 初始化夜间模式状态
         /// 从注册表读取主题设置并应用相应的主题
         /// </summary>
         private void InitializeDarkMode()
         {
             try
             {
                 // 读取主题设置
                 using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\MemGuardian"))
                 {
                     if (key != null)
                     {
                         object? themeModeValue = key.GetValue("ThemeMode");
                         int themeMode = themeModeValue != null ? Convert.ToInt32(themeModeValue) : 0; // 默认：浅色主题
                         
                         // 根据主题设置确定是否使用深色模式
                         switch (themeMode)
                         {
                             case 0: // 浅色主题
                                 isDarkMode = false;
                                 break;
                             case 1: // 深色主题
                                 isDarkMode = true;
                                 break;
                             case 2: // 自动（跟随系统）
                                 isDarkMode = IsSystemDarkMode();
                                 break;
                             default:
                                 isDarkMode = false;
                                 break;
                         }
                     }
                     else
                     {
                         // 如果没有设置，默认使用浅色主题
                         isDarkMode = false;
                     }
                 }
                 
                 ApplyDarkModeTheme(isDarkMode);
             }
             catch
             {
                 // 如果无法读取状态，默认设为浅色主题
                 isDarkMode = false;
                 ApplyDarkModeTheme(false);
             }
         }

        /// <summary>
        /// 从主窗体同步夜间模式状态
        /// 当从主窗体打开设置窗口时，确保主题一致
        /// </summary>
        private void SyncDarkModeFromMainForm()
        {
            try
            {
                if (mainForm != null)
                {
                    // 从主窗体获取当前夜间模式状态
                    bool mainFormDarkMode = mainForm.IsDarkModeEnabled();
                    if (mainFormDarkMode != isDarkMode)
                    {
                        isDarkMode = mainFormDarkMode;
                        ApplyDarkModeTheme(isDarkMode);
                    }
                }
            }
            catch
            {
                // 静默处理同步失败
            }
        }

        /// <summary>
        /// 检查是否已开启夜间模式
        /// </summary>
        /// <returns>如果已开启夜间模式返回true，否则返回false</returns>
        private bool IsDarkModeEnabled()
        {
            try
            {
                // 从注册表读取夜间模式设置
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\MemGuardian"))
                {
                    if (key != null)
                    {
                        object? value = key.GetValue("DarkMode");
                        return value != null && Convert.ToBoolean(value);
                    }
                }
            }
            catch
            {
                // 如果读取失败，返回false
            }
            return false;
        }

        /// <summary>
        /// 应用夜间模式主题
        /// 根据夜间模式状态设置窗体及其控件的颜色
        /// </summary>
        /// <param name="isDark">是否为夜间模式</param>
        private void ApplyDarkModeTheme(bool isDark)
        {
            try
            {
                if (isDark)
                {
                    // 夜间模式配色
                    this.BackColor = Color.FromArgb(32, 32, 32);
                    
                    // 左侧面板
                    leftPanel.BackColor = Color.FromArgb(23, 23, 23);
                    leftPanel.ForeColor = Color.White;
                    leftPanel.BorderStyle = BorderStyle.FixedSingle;
                    
                    // 右侧面板
                    rightPanel.BackColor = Color.FromArgb(32, 32, 32);
                    rightPanel.ForeColor = Color.White;
                    
                    // 分类列表框
                    categoryListBox.BackColor = Color.FromArgb(23, 23, 23);
                    categoryListBox.ForeColor = Color.White;
                    categoryListBox.BorderStyle = BorderStyle.FixedSingle;
                    
                    // 确保ListBox的绘制模式正确，以便显示自定义颜色
                    categoryListBox.DrawMode = DrawMode.OwnerDrawFixed;
                    
                     // 按钮 - 无背景色，悬停时显示红色，带圆角边框
                     saveButton.BackColor = Color.Transparent;
                     saveButton.ForeColor = Color.White;
                     saveButton.FlatStyle = FlatStyle.Flat;
                     saveButton.FlatAppearance.BorderSize = 1;
                     saveButton.FlatAppearance.BorderColor = Color.FromArgb(200, 200, 200);
                     saveButton.FlatAppearance.MouseOverBackColor = Color.FromArgb(255, 77, 79);
                     
                     cancelButton.BackColor = Color.Transparent;
                     cancelButton.ForeColor = Color.White;
                     cancelButton.FlatStyle = FlatStyle.Flat;
                     cancelButton.FlatAppearance.BorderSize = 1;
                     cancelButton.FlatAppearance.BorderColor = Color.FromArgb(200, 200, 200);
                     cancelButton.FlatAppearance.MouseOverBackColor = Color.FromArgb(255, 77, 79);
                    
                    // 设置标题栏为暗色
                    SetDarkTitleBar(true);
                }
                else
                {
                    // 浅色主题配色（默认）
                    this.BackColor = Color.White;
                    
                    // 左侧面板
                    leftPanel.BackColor = Color.FromArgb(240, 240, 240);
                    leftPanel.ForeColor = Color.Black;
                    leftPanel.BorderStyle = BorderStyle.FixedSingle;
                    
                    // 右侧面板
                    rightPanel.BackColor = Color.White;
                    rightPanel.ForeColor = Color.Black;
                    
                    // 分类列表框
                    categoryListBox.BackColor = Color.White;
                    categoryListBox.ForeColor = Color.Black;
                    categoryListBox.BorderStyle = BorderStyle.FixedSingle;
                    
                     // 按钮 - 无背景色，悬停时显示浅蓝色，带圆角边框
                     saveButton.BackColor = Color.Transparent;
                     saveButton.ForeColor = Color.Black;
                     saveButton.FlatStyle = FlatStyle.Flat;
                     saveButton.FlatAppearance.BorderSize = 1;
                     saveButton.FlatAppearance.BorderColor = Color.FromArgb(200, 200, 200);
                     saveButton.FlatAppearance.MouseOverBackColor = Color.FromArgb(230, 244, 255);
                     
                     cancelButton.BackColor = Color.Transparent;
                     cancelButton.ForeColor = Color.Black;
                     cancelButton.FlatStyle = FlatStyle.Flat;
                     cancelButton.FlatAppearance.BorderSize = 1;
                     cancelButton.FlatAppearance.BorderColor = Color.FromArgb(200, 200, 200);
                     cancelButton.FlatAppearance.MouseOverBackColor = Color.FromArgb(230, 244, 255);
                    
                    // 设置标题栏为浅色
                    SetDarkTitleBar(false);
                }
                
                // 更新所有控件的主题
                UpdateControlsTheme(isDark);
            }
            catch (Exception ex)
            {
                // 静默处理主题应用错误
                System.Diagnostics.Debug.WriteLine($"应用设置窗口主题错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新所有控件的主题
        /// 递归设置所有控件的颜色以匹配当前主题
        /// </summary>
        /// <param name="isDark">是否为夜间模式</param>
        private void UpdateControlsTheme(bool isDark)
        {
            try
            {
                Color foreColor = isDark ? Color.White : Color.Black;
                Color backColor = isDark ? Color.FromArgb(23, 23, 23) : Color.White;
                
                // 更新所有控件的颜色
                UpdateControlTheme(this, isDark, foreColor, backColor);
            }
            catch
            {
                // 静默处理控件主题更新错误
            }
        }

        /// <summary>
        /// 递归更新控件的主题
        /// </summary>
        /// <param name="control">要更新的控件</param>
        /// <param name="isDark">是否为夜间模式</param>
        /// <param name="foreColor">前景色</param>
        /// <param name="backColor">背景色</param>
        private void UpdateControlTheme(Control control, bool isDark, Color foreColor, Color backColor)
        {
            try
            {
                // 跳过按钮，它们有特殊的颜色设置
                if (!(control is Button))
                {
                    control.ForeColor = foreColor;
                    if (control is Panel || control is GroupBox || control is Label)
                    {
                        control.BackColor = backColor;
                    }
                    
                    // 特别处理ListBox控件，确保字体颜色正确设置
                    if (control is ListBox listBox)
                    {
                        listBox.ForeColor = foreColor;
                        listBox.BackColor = isDark ? Color.FromArgb(23, 23, 23) : Color.White;
                    }
                    
                    // 特别处理ComboBox控件
                    if (control is ComboBox comboBox)
                    {
                        if (isDark)
                        {
                            // 夜间模式：下拉选项背景为黑色，字体为白色
                            comboBox.BackColor = Color.Black;
                            comboBox.ForeColor = Color.White;
                        }
                        else
                        {
                            // 浅色模式：保持默认样式
                            comboBox.BackColor = Color.White;
                            comboBox.ForeColor = Color.Black;
                        }
                    }
                    
                    // 特别处理CheckBox控件
                    if (control is CheckBox checkBox)
                    {
                        // 跳过UAC复选框，它有特殊的颜色处理逻辑
                        if (checkBox != skipUacPromptCheckBox)
                    {
                        checkBox.ForeColor = foreColor;
                        }
                        // CheckBox背景保持透明
                    }
                    
                    // 特别处理Label控件（除了分类标题）
                    if (control is Label label)
                    {
                        // 只有非分类标题的Label才更新颜色
                        if (label.ForeColor != Color.FromArgb(33, 150, 243))
                        {
                            label.ForeColor = foreColor;
                        }
                    }
                    
                    // 特别处理NumericUpDown控件
                    if (control is NumericUpDown numericUpDown)
                    {
                        if (isDark)
                        {
                            numericUpDown.BackColor = Color.White;
                            numericUpDown.ForeColor = Color.Black;
                        }
                        else
                        {
                            numericUpDown.BackColor = Color.White;
                            numericUpDown.ForeColor = Color.Black;
                        }
                    }
                }
                
                // 递归更新子控件
                foreach (Control childControl in control.Controls)
                {
                    UpdateControlTheme(childControl, isDark, foreColor, backColor);
                }
            }
            catch
            {
                // 静默处理单个控件主题更新错误
            }
        }

        /// <summary>
        /// 设置夜间模式标题栏
        /// 使用DWM API设置窗口标题栏为暗色或浅色
        /// </summary>
        /// <param name="isDark">是否为夜间模式</param>
        private void SetDarkTitleBar(bool isDark)
        {
            try
            {
                // 确保窗口句柄已创建
                if (this.Handle == IntPtr.Zero)
                {
                    this.HandleCreated += (sender, e) => SetDarkTitleBar(isDark);
                    return;
                }

                // 设置DWM属性
                int darkMode = isDark ? 1 : 0;
                int result = DwmSetWindowAttribute(this.Handle, DWMWA_USE_IMMERSIVE_DARK_MODE, ref darkMode, sizeof(int));
                
                // 如果失败，尝试旧版本的API
                if (result != 0)
                {
                    DwmSetWindowAttribute(this.Handle, DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1, ref darkMode, sizeof(int));
                }
            }
            catch
            {
                // 静默处理标题栏设置错误
            }
        }

        /// <summary>
        /// DWM属性常量：使用沉浸式暗色模式（Windows 11 21H2及以后版本）
        /// </summary>
        private const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;

        /// <summary>
        /// DWM属性常量：使用沉浸式暗色模式（Windows 10 20H1及之前版本）
        /// </summary>
        private const int DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 = 19;

        /// <summary>
        /// 设置窗口属性的DWM API
        /// </summary>
        [System.Runtime.InteropServices.DllImport("dwmapi.dll")]
        private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);

         /// <summary>
         /// 公共方法：从外部更新夜间模式状态
         /// 当主窗体的夜间模式状态改变时调用
         /// </summary>
         /// <param name="isDark">是否为夜间模式</param>
         public void UpdateDarkMode(bool isDark)
         {
             try
             {
                 if (isDark != isDarkMode)
                 {
                     isDarkMode = isDark;
                     ApplyDarkModeTheme(isDark);
                     
                     // 更新跳过UAC选项的文本颜色
                     UpdateSkipUacPromptCheckBoxTextColor();
                 }
             }
             catch
             {
                 // 静默处理夜间模式更新错误
             }
         }

         /// <summary>
         /// 更新窗口置顶状态
         /// 当主窗口置顶状态改变时，设置窗口也应该相应更新
         /// </summary>
         /// <param name="isTopMost">是否置顶</param>
         public void UpdateTopMostStatus(bool isTopMost)
         {
             try
             {
                 this.TopMost = isTopMost;
             }
             catch
             {
                 // 静默处理置顶状态更新错误
             }
         }

         /// <summary>
         /// 同步主题选择框的选中状态
         /// 当主窗口的夜间模式状态改变时，同步更新主题选择框
         /// </summary>
         /// <param name="isDarkMode">是否为夜间模式</param>
         public void SyncThemeComboBox(bool isDarkMode)
         {
             try
             {
                 if (themeComboBox != null)
                 {
                     // 根据夜间模式状态设置主题选择框的选中索引
                     if (isDarkMode)
                     {
                         themeComboBox.SelectedIndex = 1; // 深色主题
                     }
                     else
                     {
                         themeComboBox.SelectedIndex = 0; // 浅色主题
                     }
                 }
             }
             catch
             {
                 // 静默处理主题选择框同步错误
             }
         }
         
         /// <summary>
         /// 检测系统是否使用深色主题
         /// 通过检查Windows注册表来检测系统主题设置
         /// </summary>
         /// <returns>如果系统使用深色主题返回true，否则返回false</returns>
         private bool IsSystemDarkMode()
         {
             try
             {
                 // 检查Windows 10/11的深色主题设置
                 using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize"))
                 {
                     if (key != null)
                     {
                         object? value = key.GetValue("AppsUseLightTheme");
                         if (value != null)
                         {
                             // AppsUseLightTheme为0表示深色主题，1表示浅色主题
                             return Convert.ToInt32(value) == 0;
                         }
                     }
                 }
                 
                 // 如果无法检测，默认返回false（浅色主题）
                 return false;
             }
             catch
             {
                 // 如果检测失败，默认返回false（浅色主题）
                 return false;
             }
         }
         
         /// <summary>
         /// 应用主题设置
         /// 根据用户选择的主题模式应用相应的主题
         /// </summary>
         private void ApplyThemeSetting()
         {
             try
             {
                 bool shouldUseDarkMode = false;
                 
                 switch (themeComboBox.SelectedIndex)
                 {
                     case 0: // 浅色主题
                         shouldUseDarkMode = false;
                         break;
                     case 1: // 深色主题
                         shouldUseDarkMode = true;
                         break;
                     case 2: // 自动（跟随系统）
                         shouldUseDarkMode = IsSystemDarkMode();
                         break;
                     default:
                         shouldUseDarkMode = false;
                         break;
                 }
                 
                 // 应用主题
                 if (shouldUseDarkMode != isDarkMode)
                 {
                     isDarkMode = shouldUseDarkMode;
                     ApplyDarkModeTheme(isDarkMode);
                 }
             }
             catch
             {
                 // 静默处理主题应用错误
             }
         }

         /// <summary>
         /// ComboBox自定义绘制事件处理
         /// 根据当前主题绘制ComboBox的选项和下拉箭头
         /// </summary>
         /// <param name="sender">事件发送者</param>
         /// <param name="e">绘制事件参数</param>
         private void ComboBox_DrawItem(object? sender, DrawItemEventArgs e)
         {
             if (e.Index < 0) return;

             var comboBox = sender as ComboBox;
             if (comboBox == null) return;

             // 获取项目文本
             string text = comboBox.Items[e.Index].ToString() ?? "";

             // 设置绘制参数
             e.DrawBackground();

             // 判断是否选中
             bool isSelected = (e.State & DrawItemState.Selected) == DrawItemState.Selected;

             // 根据夜间模式状态设置颜色
             Color backColor, textColor, arrowColor;
             
             if (isDarkMode)
             {
                 // 夜间模式配色
                 backColor = isSelected ? Color.FromArgb(0, 120, 215) : Color.Black;
                 textColor = Color.White; // 夜间模式下文字始终为白色
                 arrowColor = Color.White; // 夜间模式下箭头为白色
             }
             else
             {
                 // 浅色模式配色
                 backColor = isSelected ? Color.FromArgb(0, 120, 215) : Color.White;
                 textColor = isSelected ? Color.White : Color.Black;
                 arrowColor = Color.Black; // 浅色模式下箭头为黑色
             }

             // 绘制背景
             using (SolidBrush backBrush = new SolidBrush(backColor))
             {
                 e.Graphics.FillRectangle(backBrush, e.Bounds);
             }

             // 绘制文本
             using (SolidBrush textBrush = new SolidBrush(textColor))
             {
                 StringFormat sf = new StringFormat();
                 sf.Alignment = StringAlignment.Near;
                 sf.LineAlignment = StringAlignment.Center;
                 if (e.Font != null)
                 {
                     e.Graphics.DrawString(text, e.Font, textBrush, e.Bounds, sf);
                 }
             }

             // 绘制下拉箭头（仅在ComboBox主区域，不是下拉列表项）
             if (e.Index == -1) // -1表示绘制ComboBox的主区域
             {
                 DrawComboBoxArrow(e.Graphics, e.Bounds, arrowColor);
             }

             // 绘制焦点矩形
             e.DrawFocusRectangle();
         }

         /// <summary>
         /// 绘制ComboBox的下拉箭头
         /// </summary>
         /// <param name="graphics">绘图对象</param>
         /// <param name="bounds">绘制区域</param>
         /// <param name="arrowColor">箭头颜色</param>
         private void DrawComboBoxArrow(Graphics graphics, Rectangle bounds, Color arrowColor)
         {
             // 计算箭头的位置和大小
             int arrowWidth = 8;
             int arrowHeight = 6;
             int arrowX = bounds.Right - arrowWidth - 8; // 距离右边8像素
             int arrowY = bounds.Top + (bounds.Height - arrowHeight) / 2; // 垂直居中

             // 创建箭头路径
             using (GraphicsPath arrowPath = new GraphicsPath())
             {
                 Point[] arrowPoints = new Point[]
                 {
                     new Point(arrowX, arrowY),
                     new Point(arrowX + arrowWidth, arrowY),
                     new Point(arrowX + arrowWidth / 2, arrowY + arrowHeight)
                 };
                 arrowPath.AddPolygon(arrowPoints);

                 // 绘制箭头
                 using (SolidBrush arrowBrush = new SolidBrush(arrowColor))
                 {
                     graphics.FillPath(arrowBrush, arrowPath);
                 }
             }
         }
         #endregion

        #region UAC相关方法
        /// <summary>
        /// 检查当前程序是否以管理员权限运行
        /// </summary>
        /// <returns>如果以管理员权限运行返回true，否则返回false</returns>
        private bool IsRunningAsAdministrator()
        {
            try
            {
                WindowsIdentity identity = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                return principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 检查是否已开启跳过UAC提示
        /// </summary>
        /// <returns>如果已开启跳过UAC提示返回true，否则返回false</returns>
        private bool IsSkipUacPromptEnabled()
        {
            try
            {
                // 从注册表读取跳过UAC提示设置
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\MemGuardian"))
                {
                    if (key != null)
                    {
                        object? value = key.GetValue("SkipUacPrompt");
                        return value != null && Convert.ToBoolean(value);
                    }
                }
            }
            catch
            {
                // 如果读取失败，默认返回false
            }
            return false;
        }

        /// <summary>
        /// 初始化跳过UAC提示状态
        /// </summary>
        private void InitializeSkipUacPromptStatus()
        {
            try
            {
                if (skipUacPromptCheckBox != null)
                {
                    bool isSkipUacPrompt = IsSkipUacPromptEnabled();
                    skipUacPromptCheckBox.Checked = isSkipUacPrompt;
                    
                    // 记录程序启动时的UAC跳过状态
                    skipUacPromptAtStartup = isSkipUacPrompt;
                    
                    // 设置UAC勾选框的启用状态
                    UpdateSkipUacPromptCheckBoxEnabled();
                }
            }
            catch
            {
                if (skipUacPromptCheckBox != null)
                {
                    skipUacPromptCheckBox.Checked = false;
                    skipUacPromptAtStartup = false;
                    UpdateSkipUacPromptCheckBoxEnabled();
                }
            }
        }

        /// <summary>
        /// 更新跳过UAC提示复选框的启用状态
        /// 逻辑：
        /// 1. 如果软件启动后，UAC没有勾选启用并且没有管理员权限，则UAC勾选框为禁用状态
        /// 2. 如果软件启动后，UAC已经勾选启用但是没有管理员权限，此时UAC勾选框可以正常勾选
        /// 3. 如果有管理员权限，UAC勾选框始终可用
        /// </summary>
        private void UpdateSkipUacPromptCheckBoxEnabled()
        {
            try
            {
                if (skipUacPromptCheckBox == null) return;

                bool hasAdminRights = IsRunningAsAdministrator();
                bool currentSkipUac = IsSkipUacPromptEnabled();
                
                if (hasAdminRights)
                {
                    // 如果有管理员权限，UAC勾选框始终可用
                    skipUacPromptCheckBox.Enabled = true;
                }
                else
                {
                    // 如果没有管理员权限
                    if (skipUacPromptAtStartup)
                    {
                        // 如果程序启动时UAC已经勾选启用，此时UAC勾选框可以正常勾选
                        skipUacPromptCheckBox.Enabled = true;
                    }
                    else
                    {
                        // 如果程序启动时UAC没有勾选启用，则UAC勾选框为禁用状态
                        skipUacPromptCheckBox.Enabled = false;
                    }
                }
                
                // 更新文本颜色，根据启用状态和主题设置
                UpdateSkipUacPromptCheckBoxTextColor();
            }
            catch
            {
                // 如果出现异常，默认禁用
                if (skipUacPromptCheckBox != null)
                {
                    skipUacPromptCheckBox.Enabled = false;
                    UpdateSkipUacPromptCheckBoxTextColor();
                }
            }
        }
        
        /// <summary>
        /// 更新跳过UAC提示复选框的文本颜色
        /// 根据启用状态和主题设置合适的文本颜色
        /// </summary>
        private void UpdateSkipUacPromptCheckBoxTextColor()
        {
            try
            {
                if (skipUacPromptCheckBox == null) return;
                
                // 获取当前主题状态，优先从主窗体获取，如果失败则从注册表获取
                bool currentDarkMode = isDarkMode;
                if (mainForm != null)
                {
                    currentDarkMode = mainForm.IsDarkModeEnabled();
                }
                else
                {
                    // 如果主窗体不可用，直接从注册表读取
                    try
                    {
                        using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\MemGuardian"))
                        {
                            if (key != null)
                            {
                                object? value = key.GetValue("DarkMode");
                                currentDarkMode = value != null && Convert.ToBoolean(value);
                            }
                        }
                    }
                    catch
                    {
                        // 如果注册表读取失败，使用本地变量
                        currentDarkMode = isDarkMode;
                    }
                }
                
                if (skipUacPromptCheckBox.Enabled)
                {
                    // 启用状态：根据主题设置颜色
                    skipUacPromptCheckBox.ForeColor = currentDarkMode ? Color.White : Color.FromArgb(51, 51, 51);
                }
                else
                {
                    // 禁用状态：根据主题设置颜色
                    // 在深色模式下使用更亮的灰白色，确保在深色背景上可见
                    skipUacPromptCheckBox.ForeColor = currentDarkMode ? Color.FromArgb(160, 160, 160) : Color.Gray;
                }
                
                // 强制刷新控件以确保颜色生效
                skipUacPromptCheckBox.Invalidate();
                skipUacPromptCheckBox.Update();
            }
            catch
            {
                // 静默处理错误
            }
        }

        /// <summary>
        /// 创建颜色设置面板
        /// 包含标签文本和颜色选择按钮
        /// </summary>
        /// <param name="labelText">标签文本</param>
        /// <param name="colorButton">颜色选择按钮</param>
        /// <param name="yPosition">Y坐标位置</param>
        /// <returns>创建的面板</returns>
        private Panel CreateColorSettingPanel(string labelText, Button colorButton, int yPosition)
        {
            var panel = new Panel();
            panel.Location = new Point(20, yPosition);
            panel.Size = new Size(350, 32);
            panel.BackColor = Color.Transparent;

            // 创建标签
            var label = new Label();
            label.Text = labelText;
            label.Font = new Font("微软雅黑", 10F);
            // 根据当前主题设置字体颜色
            label.ForeColor = isDarkMode ? Color.White : Color.FromArgb(51, 51, 51);
            label.AutoSize = true;
            label.Location = new Point(0, 6);
            panel.Controls.Add(label);

            // 设置颜色按钮属性
            colorButton.Size = new Size(60, 24);
            colorButton.Location = new Point(280, 4);
            colorButton.FlatStyle = FlatStyle.Flat;
            colorButton.FlatAppearance.BorderSize = 1;
            colorButton.FlatAppearance.BorderColor = Color.FromArgb(200, 200, 200);
            colorButton.Font = new Font("微软雅黑", 8F);
            colorButton.UseVisualStyleBackColor = false;
            colorButton.BackColor = Color.FromArgb(76, 175, 80); // 默认绿色
            colorButton.ForeColor = Color.White;
            colorButton.Click += ColorButton_Click;
            panel.Controls.Add(colorButton);

            return panel;
        }

        /// <summary>
        /// 颜色选择按钮点击事件处理
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void ColorButton_Click(object? sender, EventArgs e)
        {
            if (sender is Button button)
            {
                using (ColorDialog colorDialog = new ColorDialog())
                {
                    colorDialog.Color = button.BackColor;
                    colorDialog.FullOpen = true;
                    
                    if (colorDialog.ShowDialog() == DialogResult.OK)
                    {
                        button.BackColor = colorDialog.Color;
                        
                        // 保存颜色设置到注册表
                        SaveTrayIconColorSetting(button, colorDialog.Color);
                        
                        // 立即更新托盘图标
                        UpdateTrayIconColor();
                    }
                }
            }
        }

        /// <summary>
        /// 保存托盘图标颜色设置
        /// 将颜色设置保存到注册表
        /// </summary>
        /// <param name="button">颜色按钮</param>
        /// <param name="color">选择的颜色</param>
        private void SaveTrayIconColorSetting(Button button, Color color)
        {
            try
            {
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\MemGuardian"))
                {
                    if (key != null)
                    {
                        // 根据按钮类型保存对应的颜色设置
                        if (button == trayTextColorButton)
                        {
                            key.SetValue("TrayTextColor", color.ToArgb());
                        }
                        else if (button == trayNormalBackgroundColorButton)
                        {
                            key.SetValue("TrayNormalBackgroundColor", color.ToArgb());
                        }
                        else if (button == trayWarningBackgroundColorButton)
                        {
                            key.SetValue("TrayWarningBackgroundColor", color.ToArgb());
                        }
                        else if (button == trayDangerBackgroundColorButton)
                        {
                            key.SetValue("TrayDangerBackgroundColor", color.ToArgb());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"保存托盘图标颜色设置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 更新托盘图标颜色
        /// 通知主窗体立即更新托盘图标颜色
        /// </summary>
        private void UpdateTrayIconColor()
        {
            try
            {
                // 通过Application.OpenForms查找主窗体实例
                foreach (Form form in Application.OpenForms)
                {
                    if (form is Form1 mainForm)
                    {
                        // 调用主窗体的方法来更新托盘图标
                        mainForm.RefreshTrayIcon();
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                // 静默处理错误，避免影响用户操作
                System.Diagnostics.Debug.WriteLine($"更新托盘图标颜色失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 重置托盘图标颜色设置为默认值
        /// 将颜色按钮重置为默认颜色并保存到注册表
        /// </summary>
        private void ResetTrayIconColorsToDefault()
        {
            try
            {
                // 设置默认颜色
                Color defaultTextColor = Color.White; // 白色
                Color defaultNormalBackgroundColor = Color.FromArgb(76, 175, 80); // 绿色 #4CAF50
                Color defaultWarningBackgroundColor = Color.FromArgb(255, 128, 64); // 橙色 #ff8040
                Color defaultDangerBackgroundColor = Color.FromArgb(255, 87, 34); // 红色 #FF5722

                // 重置按钮颜色
                if (trayTextColorButton != null)
                {
                    trayTextColorButton.BackColor = defaultTextColor;
                    SaveTrayIconColorSetting(trayTextColorButton, defaultTextColor);
                }

                if (trayNormalBackgroundColorButton != null)
                {
                    trayNormalBackgroundColorButton.BackColor = defaultNormalBackgroundColor;
                    SaveTrayIconColorSetting(trayNormalBackgroundColorButton, defaultNormalBackgroundColor);
                }

                if (trayWarningBackgroundColorButton != null)
                {
                    trayWarningBackgroundColorButton.BackColor = defaultWarningBackgroundColor;
                    SaveTrayIconColorSetting(trayWarningBackgroundColorButton, defaultWarningBackgroundColor);
                }

                if (trayDangerBackgroundColorButton != null)
                {
                    trayDangerBackgroundColorButton.BackColor = defaultDangerBackgroundColor;
                    SaveTrayIconColorSetting(trayDangerBackgroundColorButton, defaultDangerBackgroundColor);
                }
                
                // 立即更新托盘图标
                UpdateTrayIconColor();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"重置托盘图标颜色设置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载托盘图标颜色设置
        /// 从注册表读取颜色设置并应用到颜色按钮
        /// </summary>
        /// <param name="key">注册表键</param>
        private void LoadTrayIconColorSettings(RegistryKey key)
        {
            try
            {
                // 托盘图标文本颜色 - 默认绿色 #4CAF50
                object? trayTextColorValue = key.GetValue("TrayTextColor");
                if (trayTextColorValue != null)
                {
                    trayTextColorButton.BackColor = Color.FromArgb(Convert.ToInt32(trayTextColorValue));
                }
                else
                {
                    trayTextColorButton.BackColor = Color.FromArgb(76, 175, 80); // 默认绿色
                }

                // 托盘图标正常背景颜色 - 默认青色 #00BCD4
                object? trayNormalBackgroundColorValue = key.GetValue("TrayNormalBackgroundColor");
                if (trayNormalBackgroundColorValue != null)
                {
                    trayNormalBackgroundColorButton.BackColor = Color.FromArgb(Convert.ToInt32(trayNormalBackgroundColorValue));
                }
                else
                {
                    trayNormalBackgroundColorButton.BackColor = Color.FromArgb(0, 188, 212); // 默认青色
                }

                // 托盘图标警告级别背景颜色 - 默认橙色 #ff8040
                object? trayWarningBackgroundColorValue = key.GetValue("TrayWarningBackgroundColor");
                if (trayWarningBackgroundColorValue != null)
                {
                    trayWarningBackgroundColorButton.BackColor = Color.FromArgb(Convert.ToInt32(trayWarningBackgroundColorValue));
                }
                else
                {
                    trayWarningBackgroundColorButton.BackColor = Color.FromArgb(255, 128, 64); // 默认橙色
                }

                // 托盘图标危险级别背景颜色 - 默认红色 #FF5722
                object? trayDangerBackgroundColorValue = key.GetValue("TrayDangerBackgroundColor");
                if (trayDangerBackgroundColorValue != null)
                {
                    trayDangerBackgroundColorButton.BackColor = Color.FromArgb(Convert.ToInt32(trayDangerBackgroundColorValue));
                }
                else
                {
                    trayDangerBackgroundColorButton.BackColor = Color.FromArgb(255, 87, 34); // 默认红色
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"加载托盘图标颜色设置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

    }
}
